Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

Solution: Using Two Stack

The idea is to push reverse postorder traversal to a stack. Once we have reverse postorder traversal in a stack, we can just pop all items one by one from the stack This order of printing will be in postorder because of LIFO property of stacks.

    vector<int> postorderTraversal(TreeNode* root) {
        if (!root) return {};

        vector<int> ans;
        stack<TreeNode *> s1;
        stack<TreeNode *> s2;
        s1.push(root);

        while (!s1.empty()) {
            TreeNode *node = s1.top();
            s1.pop();

            if (node->left) s1.push(node->left);
            if (node->right) s1.push(node->right);
            s2.push(node);
        }

        while (!s2.empty()) {
            ans.push_back(s2.top()->val);
            s2.pop();
        }

        return ans;
    }

Solution: Using One Stack

vector<int> postorderTraversal(TreeNode* root) {
    if (!root) return {};

    stack<TreeNode *> s;
    unordered_map<TreeNode *, bool> visited;
    vector<int> ans;
    s.push(root);

    while (!s.empty()) {
        TreeNode *node = s.top();            
        if (visited[node]) {
            ans.push_back(node->val);
            s.pop();
        } else {
            if (node->right) s.push(node->right);
            if (node->left) s.push(node->left);
            visited[node] = true;
        }
    }

    return ans;
}

Solution:

    vector<int> postorderTraversal(TreeNode* root) {
        if (!root) return {};
        vector<int> res;
        stack<TreeNode*> s{{root}};
        while (!s.empty()) {
            TreeNode *t = s.top(); s.pop();
            res.insert(res.begin(), t->val);
            if (t->left) s.push(t->left);
            if (t->right) s.push(t->right);
        }
        return res;
    }

Solution: Recursive

void postorderTraversalUtil(TreeNode *root, vector<int> &result) {
    if(root == NULL) return;
    postorderTraversalUtil(root->left, result);
    postorderTraversalUtil(root->right, result);
    result.push_back(root->val);
}

vector<int> postorderTraversal(TreeNode* root) {
    vector<int> result;
    postorderTraversalUtil(root, result);
    return result;        
}

results matching ""

    No results matching ""