Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

print binary search tree valaues in sored order  RSS feed

 
Martha Wg
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator





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
Posts: 492
Firefox Browser Linux VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Stephan van Hulst
Saloon Keeper
Posts: 7803
142
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This thread is from a few months ago. Just saying.

Hunter
 
Campbell Ritchie
Marshal
Posts: 55681
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
prithvi s zankat wrote:I thing following should work. . . .
. . . but you have made the same spelling error with Return and Void.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!