pythonbinary-treeinorderpreorderpostorder

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


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 ?


Solution

  • 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