Skip to content

Files

Latest commit

Jun 9, 2020
f2a608e · Jun 9, 2020

History

History
This branch is 2352 commits behind lzl124631x/LeetCode:master.

145. Binary Tree Postorder Traversal

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Jun 9, 2020
Jun 9, 2020
Jun 9, 2020

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?

Related Topics:
Stack, Tree

Similar Questions:

Solution 1. Recursive

// OJ: https://leetcode.com/problems/binary-tree-postorder-traversal/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
private:
    vector<int> ans;
    void dfs(TreeNode* root) {
        if (!root) return;
        dfs(root->left);
        dfs(root->right);
        ans.push_back(root->val);
    }
public:
    vector<int> postorderTraversal(TreeNode* root) {
        dfs(root);
        return ans;
    }
};

Solution 2. Iterative

// OJ: https://leetcode.com/problems/binary-tree-postorder-traversal/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        stack<TreeNode*> s;
        TreeNode *prev = NULL;
        while (root || s.size()) {
            while (root) {
                s.push(root);
                root = root->left;
            }
            root = s.top();
            if (!root->right || root->right == prev) {
                ans.push_back(root->val);
                s.pop();
                prev = root;
                root = NULL;
            } else root = root->right;
        }
        return ans;
    }
};