programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# print binary search tree valaues in sored order

Greenhorn
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.

Ranch Hand
Posts: 492
• 1
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

Saloon Keeper
Posts: 8307
148
• 1
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.

Greenhorn
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
Posts: 492
This thread is from a few months ago. Just saying.

Hunter

Marshal
Posts: 57437
175

prithvi s zankat wrote:I thing following should work. . . .

. . . but you have made the same spelling error with Return and Void.

 Why is the word "abbreviation" so long? And this ad is so short? The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS