Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this inorder traversal algorithm work?

I don't have much experience with recursion, so I'm having a hard time determining exactly how this algorithm works:

 public static void inorder(Node<?> n)
 {
  if (n != null)
  {
   inorder(n.getLeft());
   System.out.print(n.data + " ");
   inorder(n.getRight());
  }
 }

I know that it visits the left and right child nodes of every node in the tree, but I just can't get my head around why exactly it works.

like image 823
Haque1 Avatar asked May 19 '14 18:05

Haque1


People also ask

What is the algorithm for inorder traversal?

What Is InOrder Traversal Algorithm? The InOrder traversal is one of the three popular ways to traverse a binary tree data structure, the other two being the preOrder and postOrder. During the in-order traversal algorithm, the left subtree is explored first, followed by root, and finally nodes on the right subtree.

How does recursive inorder traversal work?

In an Inorder traversal, we process all the nodes of a tree by recursively processing the left subtree, then processing the root, and finally the right subtree.

What is true about inorder traversal of tree?

Uses of Inorder Traversal: In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal is reversed can be used. Example: In order traversal for the above-given figure is 4 2 5 1 3.


1 Answers

I'll try to give it a shot.

Imagine a tree

           a
      b          c
   d    e     f     g

Each letter represents a Node object.

What happens when you pass in the 'a' node is that it will look at the first left node and find 'b'. It will then call the same method on 'b' and wait until that returns

In 'b' it will look for the first left node and find 'd'. It will then call the same method on 'd' and wait until that returns

In 'd' it will look for the first left node and run the same method. Since the left node is null the function will return. It will then print out 'd' After it prints out 'd' it will call the function on the right node to 'd' which is also null and immediately return. Then that instance of the method will return back to the 'b' node function.

It will now print out 'b' then call the method on the right hand node of 'b'.

It will find node 'e' Then it will call the method on the left node of e which will be null and return. Then print out 'e'. then call the method on the right node of 'e' which is also null and return back to the 'e' method call. Then it will return out to the 'b' node.

From 'b' it will return back up to 'a', print out 'a' and start the same process on the right side of 'a'.

Eventually it will print out:

d b e a f c g

like image 190
Mark Carpenter Avatar answered Oct 29 '22 02:10

Mark Carpenter