Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes Traversing the right branch of a binary tree. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Traversing the right branch of a binary tree." Watch "Traversing the right branch of a binary tree." New topic
Author

Traversing the right branch of a binary tree.

Kezia Matthews
Ranch Hand

Joined: May 19, 2001
Posts: 107
Hi All,
I have been trying to display the information present in the nodes of a binary tree using a recursive function. I am successful in displaying the information in the nodes of the left branch of the tree. I have trouble in displaying the right branch. Can anybody help me?
I am posting the code that I used to traverse the tree.

I am sure that there is a bug, somewhere in the above code.....but, am not able to trace it! Can somebody help me?
Thanks in advance.
Kezia.
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
By the time display(root.right) is executed, "root" will have the value of "root.left" (the assignment is the last expression in your for loop). You never visit the right hand branch.
Your for loop is hard to understand, by the way. Don't use this style in real life[tm].
What about

This should dump the tree in infix notation (i.e. left branch - node - right branch). Move around the println() call for prefix or postfix.
- Peter
Kezia Matthews
Ranch Hand

Joined: May 19, 2001
Posts: 107

Hi Peter,
The code that you have posted is simple and easy to understand...and it works too! .
That was a great help.
Thanks
Kezia.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Traversing the right branch of a binary tree.
 
Similar Threads
mistake
a binary tree question..
Binary search tree questions...
Binary Search Trees
Deleting all leaves from a binary tree