LeetCode 145 Binary Tree Postorder Traversal(二叉树后序遍历)

来源:互联网 发布:恶灵附身优化怎么样 编辑:程序博客网 时间:2024/05/21 08:42

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?

题目大意:写出二叉树非递归后序遍历的方法。

解题思路:对于任意节点N:

    1. 将N入栈

    2. 如果N没有左孩子和右孩子,或者N存在左孩子或右孩子但都已经被访问过了,那么可以直接访问N

    3. 如果N存在左孩子或右孩子且还没被访问过,那么将N的右孩子和左孩子依次入栈,然后将栈顶元素置为N,重复步骤2和3

    4. 直到N为空且栈为空,遍历结束

参考资料:http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html

代码如下:

/** * Definition for a binary tree node. * 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) {        if(root == nullptr) return vector<int>();        vector<int> ans;        stack<TreeNode*> stk;        TreeNode* cur;        TreeNode* pre = nullptr;        stk.push(root);                while(stk.size()){            cur = stk.top();            if((cur->left == nullptr && cur->right == nullptr) || (pre && (pre == cur->left || pre == cur->right))){                ans.push_back(cur->val);                stk.pop();                pre = cur;            }else{                if(cur->right) stk.push(cur->right);                if(cur->left) stk.push(cur->left);            }        }        return ans;    }};

阅读全文
0 0