Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# print binary search tree valaues in sored order

Martha Wg
Greenhorn

Joined: May 17, 2011
Posts: 7

the code above is to print binary tree values in sorted order. I understand that recprint(node p) keep track p.left, so that 2(leftmost one) is printout at first step.(by executing System.out.print() method). now p points to the leftmost node. and I have no idea how the code works next...anyone could help me with the code. I am greatly appreciate any tips or suggest.
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 490

This is a recursive function, the best way to figure out what is going on in recursive functions is to get a piece of paper out and write down all of the recursive calls. I write down the first two then let you have a go at it.

Call stack:
1. recprint(root) //the root is Node 7
2. recprint(p.left) // root and p are the same at the moment, so p.left (root.left) is Node 5
3. recprint(p.left) //p is currently Node 5, what is p.left?

PS - this algorithm is doing something known as an inorder traversal, the wikipedia page for tree traversal could help eliminate some of your doubts. http://en.wikipedia.org/wiki/Tree_traversal

Hunter

"If the facts don't fit the theory, get new facts" --Albert Einstein
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3096

2
Also, note that your code should probably read 'void' and 'return', not 'Void' and 'Return'. Void is a placeholder class that may only be represented by the null reference, and Return is not defined by Java.
prithvi s zankat
Greenhorn

Joined: Jul 18, 2005
Posts: 12
I thing following should work.

Void print // print tree in order
{
recprint(root);
System.out.println();
}
Void recprint(Node p)
{
If (p == null)
Return;
recprint(p.left);
if(p.left != null)
System.out.print( p.left.value+ “ ”);
recprint(p.right);
if(p.right!= null)
System.out.print( p.right.value+ “ ”);
}
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 490

This thread is from a few months ago. Just saying.

Hunter
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 34668

13
prithvi s zankat wrote:I thing following should work. . . .
. . . but you have made the same spelling error with Return and Void.

Consider Paul's rocket mass heater.

subject: print binary search tree valaues in sored order