Categories:

Tags:



Problem

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

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

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Solution

The problem Binary Tree Postorder Traversal can be solved iteratively using a stack to store nodes in the same way as Binary Tree Preorder Traversal. However, this time, instead of the right node, left node is pushed first, resulting in a traversal which when reversed, produces a postorder traversal.

Implementation

typedef stack<TreeNode *> Stack;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
  public:
    vector<int> postorderTraversal(TreeNode *root)
    {
        Stack roots;
        roots.push(root);

        vector<int> ret;
        while (!roots.empty())
        {
            root = roots.top();
            roots.pop();
            if (root == NULL)
                continue;

            ret.push_back(root->val);
            roots.push(root->left);
            roots.push(root->right);
        }

        reverse(ret.begin(), ret.end());
        return ret;
    }
};