Binary Tree Postorder Traversal

Description

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

Example
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [3,2,1].

Challenge
Can you do it without recursion?

Method

  1. DFS
  2. x

Example

  1. 1
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Postorder in vector which contains node values.
     */
public:
    vector<int> postorderTraversal(TreeNode *root) {
        // write your code here
        if (!root) {
            return {};
        }
        vector<int> result;
        TreeNode* cur = root;
        TreeNode* lastvisit = nullptr;
        // modified from standard Depth-first-search
        stack<TreeNode*> stk;
        while (cur || !stk.empty()) {
            while (cur) {
                stk.push(cur);
                cur = cur->left;
            }
            cur = stk.top();
            // control the pop condition
            if (!cur->right || cur->right == lastvisit) {
                stk.pop();
                result.push_back(cur->val);
                lastvisit = cur;
                cur = nullptr;
            } else {
                cur = cur->right;
            }
        }
        return result;
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""