145. Binary Tree Postorder Traversal***

145. Binary Tree Postorder Traversal***

https://leetcode.com/problems/binary-tree-postorder-traversal/

题目描述

Given a binary tree, return the postorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

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

C++ 实现 1

递归的形式; 这道题被标注为 Hard 可不是为了检验你写递归的能力…

class Solution {
private:
    vector<int> res;
    void postorder(TreeNode *root) {
        if (!root) return;
        postorder(root->left);
        postorder(root->right);
        res.push_back(root->val);
    }
public:
    vector<int> postorderTraversal(TreeNode* root) {
        postorder(root);
        return res;
    }
};

C++ 实现 2

后序遍历的迭代形式和前序遍历 (144. Binary Tree Preorder Traversal**) 其实是差不多的, 如下:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if (!root) return {};
        vector<int> res;
        stack<TreeNode*> st;
        TreeNode *p = root;
        while (!st.empty() || p) {
            if (p) {
                st.push(p);
                res.push_back(p->val);
                p = p->right;
            } else {
                auto cur = st.top();
                st.pop();
                p = cur->left;
            }
        }
        std::reverse(res.begin(), res.end());
        return res;
    }
};

但区别在, 它是前序遍历 (144. Binary Tree Preorder Traversal**)的 Reverse 形式.

使用 p 表示当前访问的节点, 如果 p 不为空, 那么就加入到 res 中, 然后 p 先指向右子树, 然后再指向左子树. 这样的话, res 中存入的节点顺序是 [根节点, 右子树节点, 左子树节点], 最后只要将 res 进行翻转即可.

while 循环部分抽离出来, 并去掉栈的相关部分, 得到结果和前序遍历的结果进行对比:

// 后序遍历的结果
if (p) {
   res.push_back(p->val);
   p = p->right;
} else {
   p = cur->left;
}
std::reverse(res.begin(), res.end());

// 前序遍历的结果
if (p) {
     res.push_back(p->val);
     p = p->left;
 } else {
     p = cur->right;
 }

可以很明显的看到联系和区别.

发布了352 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104571613