mariia-kornieva
8/20/2019 - 7:00 PM

145. Binary Tree Postorder Traversal

  1. Binary Tree Postorder Traversal
// Recursive


// Iterative
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        std::vector<int> tree;
        std::stack<TreeNode*> roots;
        
        TreeNode* prev = nullptr;
        while (root || !roots.empty()) {
            if (root) {
                roots.push(root);
                root = root->left;
            } else {
                auto curr = roots.top();
                if (curr->right && prev != curr->right) {
                    root = curr->right;
                } else {
                    tree.push_back(curr->val);
                    prev = curr;
                    roots.pop();
                }
            }
        }
        
        
        return tree;
    }
};

// Morris