Sunday, December 27, 2009

Minimum of Binary Sub Tree

public Node getMinOfSubTree(Node n)
        {
            if (n.Left == null && n.Right == null) return n;
            Node t = n;
            while (t.Left != null)
            {
                t = t.Left;
            }
            return t;
        }

Maximum of Binary Sub Tree

public Node getMaxOfSubTree(Node n)
        {
            if (n.Left == null && n.Right == null) return n;
            Node t = n;
            while (t.Right != null)
            {
                t = t.Right;
            }
            return t;
        }

Next Smaller Node


public Node getNextSmaller(Node r)
{
Node t = root;
Node gp = root;
Node p = root;
t = root;

while (t != null && !r.Equals(t))
{
gp = p;
p = t;
if (r.CompareTo(t) < 0)
{
t = t.Left;

}
else
{
t = t.Right;
}

}
if (t.Data == this.getMin()) return null;
if (t.Left == null && p.Data < t.Data) return p;
if (t.Left == null && p.Data > t.Data) return gp;
if (t.Left != null && t.Left.Right != null)
{
t = t.Left.Right;
while (t.Right != null)
{
t = t.Right;
}
return t;
}
if (t.Left != null && t.Left.Right == null) return t.Left;

return null;
}

Next Greater Node

public Node getNextGreater(Node n)
{
Node t = null;
Node p = root;
t = root;
Node gp = null;
while (t != null && !n.Equals(t))
{
gp = p;
p = t;
if (n.CompareTo(t) < 0)
{
t = t.Left;

}
else
{
t = t.Right;
}

}
if (n.Data == this.getMax()) return null;
if (t.Right == null && t.Equals(p.Right)) return gp;
if (t.Right == null && t.Equals(p.Left)) return p;
if (t.Right.Left == null && t.Right.Right == null) return t.Right;
if (t.Right.Left != null) return t.Right.Left;
return null;
}

Tuesday, December 15, 2009

Count words in a sentence

public int countWords(string s1)
{
int cnt = 0;
//char space = ' ';
int i = 0;
for (i = 0; i < s1.Length; i++)
{
if (s1[i] == ' '){}
else if (s1[i] != ' ' && i == 0) cnt++;
else if (s1[i] != ' ' && s1[i - 1] != ' ') { }
else if (s1[i] != ' ' && s1[i - 1] == ' ') cnt++;
}
return cnt;
}

Node.JS rest api Tutorials