LeetCode 145. Binary Tree Postorder Traversal

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

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].


Stack Problem, One example will make this question easy to tackle.

In this example, the post-order sequence is: 4, 5, 2, 6, 31.  

The process will be.... We first push 1 onto stack, Get the top element, pop it off, then push the left and right child.....

vector<int> postorderTraversal(TreeNode* root) {
        if(!root) return {};
        vector<int> res;
        stack<TreeNode*> nodes;
        nodes.push(root);
        while(!nodes.empty()) {
            TreeNode* tmp = nodes.top();
            nodes.pop();
            res.push_back(tmp->val);
            if(tmp->left) nodes.push(tmp->left);
            if(tmp->right) nodes.push(tmp->right);
        }
        reverse(res.begin(), res.end());
        return res;
    }


Another way of asking this question is to implement a post-order iterator which has getNext() method, and hasNext() method.

   1
  / \
 4   2
    / \
   3   6   The post order is: 4 3 6 2 1 (left substree, root, right substree)
class postOrderIterator {
  stack<TreeNode*> nodes;

public:
  void findNextLeave(TreeNode* root) {
    TreeNode* curr = root;
    while(curr) {
      nodes.push_back(curr);
      if(curr->left) curr = curr->left;
      else if(curr->right) curr = curr->right;
    }
  }

  bool hasNext() {
    return !nodes.empty();
  }

  int getNext() {
    TreeNode* res = nodes.top();
    nodes.pop();
    while(!nodes.empty()) {
      TreeNode* tmp = nodes.top();
      if(res == tmp->left) {  // left is done, traversal the right.
        findNextLeave(tmp->right);
      }
    }
    return res->val;
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值