| Author |
Insert numbers in a binary search tree
|
rebps arora
Greenhorn
Joined: Oct 13, 2011
Posts: 3
|
|
Hi I am trying to make binary search tree...I am trying to construct the left part of binary search tree with root node set as 70...It is not working ...Can someone please make changes in code so that it works fine...My code is
public class Node {
/**
* @param args
*/
int root;
Node left;
Node right;
public void insertNode(Node node, int num) {
//Node nodeRoot = this;
//root of tree we have set to 70...constructing only left of tree with root=70
if(num<node.root)
{
while(node.left!=null)
{
node=node.left;
//suppose we insert 56 that goes to left of 70 but after that we insert 60
if(num>node.root)
{
Node temp = new Node();
temp.root = num;
node.right = temp;
System.out.println(num + "" + "at right of" +node.root);
}
}
//some condition is required here.....
Node temp = new Node();
temp.root = num;
node.left = temp;
System.out.println(num + "" + "at left of" +node.root);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node node = new Node();
node.root=70;
System.out.println("building tree with" + "" + node.root);
// node = node.insert(node, 70);
node.insertNode(node, 56);
/* node.insertNode(node, 45);
node.insertNode(node, 15);
node.insertNode(node, 16);
node.insertNode(node, 60);
node.insertNode(node, 80);
node.insertNode(node, 85);*/
/*node.insertNode(node, 45);
node.insertNode(node, 56);
node.insertNode(node, 16);
node.insertNode(node, 15);
node.insertNode(node, 60);
node.insertNode(node, 80);
node.insertNode(node, 85);*/
}
}
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
Hi Rebs,
Welcome to the Ranch
To get better help please TellTheDetails since ItDoesntWorkIsUseless
Can someone please make changes in code so that it works fine
I doubt any one will provide direct solution rather than help you find it... So please tell as what is your intention and where you are struck exactly.
I have added some Code Tags to your code and removed commented lines to make it look clearer.
|
 |
rebps arora
Greenhorn
Joined: Oct 13, 2011
Posts: 3
|
|
Hi John,
What i expect is:
If i call
node.insertNode(node, 56);
node.insertNode(node, 59);
node.insertNode(node, 45);
node.insertNode(node, 43);
The output should be:
56 at left of 70
59 at right of 56
45 at left of 56
43 at left of 45
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32694
|
|
|
I prefer the recursive approach
|
 |
rebps arora
Greenhorn
Joined: Oct 13, 2011
Posts: 3
|
|
Hi Campbell/John
Can you please help me in doing the same by non recursive method.
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
If you don't want to use a recursive method, you have to use a flag to check whether the addition of the new node is done.
The steps might not be clear. Let me take a try though.
Note that you have to implement code when the number is greater than the passed node's root...
|
 |
 |
|
|
subject: Insert numbers in a binary search tree
|
|
|