Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post order traversal of binary tree without recursion

What is the algorithm for doing a post order traversal of a binary tree WITHOUT using recursion?

like image 394
Patrik Svensson Avatar asked Aug 18 '09 15:08

Patrik Svensson


People also ask

How do you traverse a binary tree in post-order traversal without recursion?

PostOrder Traversal without Recursion is a traversal method, where the left subtree is visited first, then right sub tree, and finally root node. Unlike array and linked lists, being linear data structures, we have several ways of traversing binary tree due to its hierarchical nature.

Can you traverse a tree without recursion?

Solution: Morris Traversal Morris Traversal is a method based on the idea of a threaded binary tree and can be used to traverse a tree without using recursion or stack.

How do you solve post-order traversal?

The idea is to move down to leftmost node using left pointer. While moving down, push root and root's right child to stack. Once we reach leftmost node, print it if it doesn't have a right child. If it has a right child, then change root so that the right child is processed before.

What is the post-order traversal of following binary tree?

The postorder traversal is one of the traversing techniques used for visiting the node in the tree. It follows the principle LRN (Left-right-node). Postorder traversal is used to get the postfix expression of a tree. Traverse the left subtree by calling the postorder function recursively.


1 Answers

Here's the version with one stack and without a visited flag:

private void postorder(Node head) {   if (head == null) {     return;   }   LinkedList<Node> stack = new LinkedList<Node>();   stack.push(head);    while (!stack.isEmpty()) {     Node next = stack.peek();      boolean finishedSubtrees = (next.right == head || next.left == head);     boolean isLeaf = (next.left == null && next.right == null);     if (finishedSubtrees || isLeaf) {       stack.pop();       System.out.println(next.value);       head = next;     }     else {       if (next.right != null) {         stack.push(next.right);       }       if (next.left != null) {         stack.push(next.left);       }     }   } } 
like image 183
tcb Avatar answered Sep 22 '22 08:09

tcb