Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
February 12th, 2013, 09:28 AM
 memo0o0
Registered User

Join Date: Feb 2013
Posts: 10
Time spent in forums: 52 m 13 sec
Reputation Power: 0

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;
}
}```

#2
February 12th, 2013, 10:31 AM
 Jacques1
You have been warned

Join Date: Jul 2012
Posts: 3,108
Time spent in forums: 2 Months 3 Weeks 4 Days 14 h 42 m 57 sec
Reputation Power: 1063
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).

#3
February 12th, 2013, 07:42 PM
 NormR
Contributing User

Join Date: Aug 2010
Location: SW Missouri
Posts: 3,582
Time spent in forums: 2 Weeks 3 Days 2 h 49 m 10 sec
Reputation Power: 347

 Viewing: Dev Shed Forums > Programming Languages > Java Help > Help me please