【Leetcode】145.二叉树的后序遍历C++(严格遍历法)

在这里插入图片描述在这里插入图片描述


#include "iostream"

#include "vector"

#include "stack"

#include "unordered_set"

using namespace std;

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> ans;
        stack<TreeNode *> path;
        unordered_set<TreeNode *> map; // 记录已经访问的结点
        TreeNode *current;
        bool left, right;

        if (root)
        {
            path.push(root);
        }

        while (!path.empty())
        {
            current = path.top(); // 分别访问上一次放入的左右两个节点

            // 左右结点判断先后顺序不能互换,因为需要先把右结点放进 stack中
            if (current->right && map.find(current->right) == map.end())
            {
                right = false;
                path.push(current->right);
            }
            else
            {
                // 右节点为空或者已访问
                right = true;
            }

            if (current->left && map.find(current->left) == map.end())
            {
                left = false;
                path.push(current->left);
            }
            else
            {
                // 左节点为空或者已访问
                left = true;
            }

            if (left && right)
            {
                // 左右结点已经访问过了或者是叶子节点
                // 才可以访问当前结点
                ans.push_back(current->val);
                map.insert(current);
                path.pop(); // 访问过了,从path中移除
            }
        }

        return ans;
    }
};
发布了103 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104102616