码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Binary Tree Postorder Traversal 二叉树的后序遍历

时间:2015-01-27 01:51:12      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

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].

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

 

经典题目,求二叉树的后序遍历的非递归方法,跟前序,中序,层序一样都需要用到栈,后续的顺序是左-右-根,所以当一个节点值被取出来时,它的左右子节点要么不存在,要么已经被访问过了。具体思路可参见神网友 Yu‘s Coding Garden 的博客,代码如下:

 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        if (!root) return res;
        stack<TreeNode*> s;
        s.push(root);
        TreeNode *head = root;
        while (!s.empty()) {
            TreeNode *top = s.top();
            if ((!top->left && !top->right) || top->left == head || top->right == head) {
                res.push_back(top->val);
                s.pop();
                head = top;
            } else {
                if (top->right) s.push(top->right);
                if (top->left) s.push(top->left);
            }
        }
        return res;
    }
};

 

[LeetCode] Binary Tree Postorder Traversal 二叉树的后序遍历

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4251757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!