LeetCode 145 二叉树的后序遍历

发布时间 2023-04-03 13:30:24作者: 卑以自牧lq

LeetCode | 145.二叉树的后序遍历

给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。

示例 1:
    1
     \
      2
     /
    3 
输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2:

输入:root = []
输出:[]
示例 3:

输入:root = [1]
输出:[1]

提示:

  • 树中节点的数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

迭代:

vector<int> postorderTraversal(TreeNode* root) {
    if (!root) 
        return {};
    vector<int> res;
    stack<TreeNode*> st;
    TreeNode* pre = nullptr;
    while (root || !st.empty()) {
        while (root) {
            st.push(root);
            root = root->left;
        }
        root = st.top();
        st.pop();
        if (!root->right || root->right == pre) {
            res.push_back(root->val);
            pre = root;
            root = nullptr;
        } else {
            st.push(root);
            root = root->right;
        }
    }
    return res;
}

递归:

void helper(TreeNode* root, vector<int> &res) {
    if (!root)
        return;
    helper(root->left, res);
    helper(root->right, res);
    res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
    vector<int> res;
    helper(root, res);
    return res;
}

mirrors 算法:
设当前节点为 cur
没有左节点
 直接遍历右节点
有左节点
 找到左节点的最右的子节点
  如果最右节点的右节点为空 (最右节点的右节点不一定为空,因为我们会令它指向 cur 节点)
   令右节点指向 cur, 遍历 cur 的左节点
  如果最右节点的右节点不为空,说明 cur 的左节点已经遍历完
   断开最右节点和 cur 的连接,开始遍历 cur 的右节点
后序遍历比前序和中序要复杂一点,要遍历完左右节点才添加中间节点

void addPath(vector<int> &vec, TreeNode *node) {
    int count = 0;
    while (node != nullptr) {
        ++count;
        vec.emplace_back(node->val);
        node = node->right;
    }
    reverse(vec.end() - count, vec.end());
}

vector<int> postorderTraversal(TreeNode *root) {
    vector<int> res;
    if (root == nullptr) {
        return res;
    }

    TreeNode *cur = root, *rightmost = nullptr;

    while (cur != nullptr) {
        if (cur->left != nullptr) {
            rightmost = cur->left;
            while (rightmost->right != nullptr && rightmost->right != cur) {
                rightmost = rightmost->right;
            }
            if (rightmost->right == nullptr) { // 左节点还没有遍历
                rightmost->right = cur;
                cur = cur->left;
                continue;
            } else { // 左节点遍历完
                rightmost->right = nullptr;
                addPath(res, cur->left); // 左节点遍历完后添加到数组
            }
        }
        cur = cur->right;
    }
    addPath(res, root);
    return res;
}