Skip to content

[LeetCode] 145. 二叉树的后序遍历 #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Aug 14, 2019 · 0 comments
Open

[LeetCode] 145. 二叉树的后序遍历 #43

Animenzzzz opened this issue Aug 14, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [3,2,1]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

解题思路:使用栈后序遍历,左-右-根。其中head节点是为了记录上一个处理过的节点,因为是后序遍历,所以node会是根节点,head为其叶子节点

C++解题:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if(!root) return {};
        vector<int> result;
        stack<TreeNode *> ss;
        TreeNode* head = root;
        ss.push(root);
        while (!ss.empty())
        {
            TreeNode* node = ss.top();
            if ((!node->left && !node->right) || node->left == head || node->right == head)
            {
                result.push_back(node->val);
                ss.pop();
                head = node;
            }else{
                if(node->right) ss.push(node->right);
                if(node->left) ss.push(node->left);
            }
        }
        return result;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant