Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion in tree traversal

I'm new to the concept of graphs and trees.Below is the inorder tree traversal of tree.

 if(n!=null){
     treeTraversal(n.left);
     System.out.println(n.val);
     treeTraversal(n.right);
 }

I'm not able to understand the flow as it involves recursion. Can somebody explain me how does control flow takes place with respect to stack.

like image 280
rampuriyaaa Avatar asked Apr 15 '26 01:04

rampuriyaaa


1 Answers

Let's say I have a tree which is something like:

    4
   / \
  2   5
 / \
1   3

Your code will first put the recurse through the left children 4 -> 2 -> 1. Since 1 does not have a left child (it is null), it will print 1 and then pop the stack. Next up in the recursion is 2. It will print 2 then traverse the right child of 2 i.e 3. It will print 3, then pop the stack. Then it will print 4, then 4's right child 5. The sequence of prints will be 1, 2, 3, 4, 5. Here is a good animation too.

like image 50
ApprenticeHacker Avatar answered Apr 17 '26 16:04

ApprenticeHacker