Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Traversing the right branch of a binary tree.

 
Kezia Matthews
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic