February 12th, 2013, 09:28 AM

Help me please
I have binart tree and ihave two method i can not solve them can anyone help ??
this my code and the methods are
public int less (int n)
public int nth(int n)
the first one return how many number less than n in tree
the second return the element that found at location n
if the tree sort in ascending order in array??
Code:
public class BST
{ private BTNode<Integer> root;
public BST()
{ root = null;
}
public boolean find(Integer i)
{ BTNode<Integer> n = root;
boolean found = false;
while (n!=null && !found)
{ int comp = i.compareTo(n.data);
if (comp==0)
found = true;
else if (comp<0)
n = n.left;
else
n = n.right;
}
return found;
}
public boolean insert(Integer i)
{ BTNode<Integer> parent = root, child = root;
boolean goneLeft = false;
while (child!=null && i.compareTo(child.data)!=0)
{ parent = child;
if (i.compareTo(child.data)<0)
{ child = child.left;
goneLeft = true;
}
else
{ child = child.right;
goneLeft = false;
}
}
if (child!=null)
return false; // number already present
else
{ BTNode<Integer> leaf = new BTNode<Integer>(i);
if (parent==null) // tree was empty
root = leaf;
else if (goneLeft)
parent.left = leaf;
else
parent.right = leaf;
return true;
}
}
public int less(int n ) // return how many number are less than n appear in tree
{
if (root == null)
return 0;
int count;
if (root.left == null) {
return 1;
}
else
count = 1;
count += root.left.int less();
return count;
}
public int nth(int n) // return the element that would be found at location n if the contents of the tree were stored in ascending order in an array; an exception of type NoSuchElementException should be thrown if such an element would not exist
{
return n;
}
}
class BTNode<T>
{ T data;
BTNode<T> left, right;
BTNode(T o)
{ data = o; left = right = null;
}
}
thank you in advance
February 12th, 2013, 10:31 AM

Hi,
so what are your own thoughts on this? If you draw a binary tree and choose some number in between, how would you count the numbers less than it?
Note that this is not a homework service. We can help you with concrete questions and ideas, but we won't write code for you (if that's what you expected).
February 12th, 2013, 07:42 PM
