can we code inorder,preorder and postorder in single code in python ? without using recursion

Question:

i want to code all binary tree orders in single code (preorder,postorder,inorder) in O(N) time complexity and O(N) space , using single stack and without recursion.

anybody can help me ?

Asked By: Rahul Jangir

||

Answers:

The below code is easy to keep in mind as we just have to change (3 lines of code), order for left-root-right as we do while using recursion.

Question was asked for Python Implementation, but as Data Structure is language Independent, I am posting this answer so others are benefited.

It is O(N) space, using single stack and without recursion

For Inorder Traversal

#include <bits/stdc++.h>
using namespace std;

struct node{
    int val;
    node *left, *right;
    node(int x) {
        val = x;
        left = right = NULL;
    }
};

void traversal_trick(node *root) {
    //inorder
    stack<pair<node*, int>> S;
    
    S.push({root, 0});
    while(!S.empty()){
        pair<node*, int> t = S.top();
        node* cur = t.first;
        int state = t.second;
        
        S.pop();

        if(cur == NULL or state == 3) continue;
        
        S.push({cur, state+1});
        
        if (state == 0) S.push({cur->left, 0});
        else if (state == 1) cout << cur->val << " " ;
        else if (state == 2) S.push({cur->right, 0});
    }
}

int main()
{
    node *root = new node(7); 
    node *t = root;
    root->left = new node(3); root->right = new node(10);
    root->left->left = new node(2); root->left->right = new node(5);
    root->left->left->left = new node(1);
    root->right->left = new node(8); 
    root->right->right = new node(12);
    
    traversal_trick(root);
}

For Preorder Traversal : Just change this part of code

        if (state == 0) cout << cur->val << " " ;
        else if (state == 1) S.push({cur->left, 0});
        else if (state == 2) S.push({cur->right, 0});

For Postorder Traversal : Just change this part of code

        if (state == 0) S.push({cur->left, 0}) ;
        else if (state == 1) S.push({cur->right, 0}) ;
        else if (state == 2) cout << cur->val << " ";

For explanation see this

Answered By: Prakhar

You can use a stack and accompany every pushed node with an order-identification ("pre", "in" or "post"). The code can then check if this matches the required traversal order to decide whether to yield the node’s value or not.

Code:

class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def traversal(self, order="pre"):
        stack = [(self, "pre")]
        while stack:
            node, nodeorder = stack.pop()
            if nodeorder == order:
                yield node.value
            if nodeorder == "pre":
                stack.append((node, "in"))
                if node.left:
                    stack.append((node.left, "pre"))
            elif nodeorder == "in":
                stack.append((node, "post"))
                if node.right:
                    stack.append((node.right, "pre"))

So traversal should get as second argument either "pre", "in" or "post", depending on the order you want.

Example tree:

         4
        / 
       2   5
      /    
     1   3   7
            /
           6

…and corresponding code:

root = Node(4,
    Node(2,
        Node(1),
        Node(3)
    ),
    Node(5,
        None,
        Node(7,
            Node(6)
        )
    )
)

print(*root.traversal("pre"))   # 4 2 1 3 5 7 6
print(*root.traversal("in"))    # 1 2 3 4 5 6 7
print(*root.traversal("post"))  # 1 3 2 6 7 5 4
Answered By: trincot

can we code inorder,preorder and postorder in single code in python ? without using recursion

Ans. Yes we can. firstly we intialize a Stack [LIFO] with the root and the number. example [(root,1)] number is specifically used to know
that this is our first time or the second time or the third time we
visited the node. also intialized the preorder, inorder, postorder to store the answer in a list

Now the main concept we will be using->

loop till stack is not empty..! (1) pop from the stack [Last in first
out]
check the value of the number let’s say number is 1 than we
append root val in preorder list and increase the number by 1 and
appending again in the stack and if there exist a left (root.left) we
will append in a stack as well with initializing number by one
.

Lets say the number is 2:

You will append root val in inorder list and increase the number by 1
and appending again in the stack and if there exist a right
(root.right) we will append in a stack as well with initializing
number by one

Lets say the number is 3:

You will append root val in postorder list. Note* when number is 3 you don’t need to again append the root you will simply pop it.. and no need to check whether it has left or right subtree..!

That’s it this logic we will be using to solve this problem

Python Code->

  #Definition for a binary tree node.
    class TreeNode:
        def __init__(self, val=0, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
    class Solution:
        def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
            #In one flow Striver
            stack=[(root,1)]
            pre,ino,post=[],[],[]
            if root==None:
                return
            while stack:
                node,nodepass=stack.pop()
                if nodepass==1:
                    pre.append(node.val)
                    nodepass+=1
                    stack.append((node,nodepass))
                    if node.left!=None:
                        stack.append((node.left,1))
                elif nodepass==2:
                    ino.append(node.val)
                    nodepass+=1
                    stack.append((node,nodepass))
                    if node.right!=None:
                        stack.append((node.right,1))
                else:
                    post.append(node.val)
                
            return pre,ino,post

You can practice this question in -> https://www.codingninjas.com/codestudio/problems/981269?topList=striver-sde-sheet-problems&utm_source=striver&utm_medium=website

Reference video to more understand about the concepts-> https://www.youtube.com/watch?v=ySp2epYvgTE

Answered By: Yash Mehta