Files
leetcode-master/problems/0145.二叉树的后序遍历.md
youngyangyang04 80f725930e Update
2020-08-10 09:46:08 +08:00

2.5 KiB
Raw Blame History

题目地址

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

思路

详细题解请看这篇:一文学通二叉树前中后序递归法与迭代法

C++代码

递归

class Solution {
public:
    void traversal(TreeNode* root, vector<int>& vec) {
        if (root == NULL) return;
        traversal(root->left, vec);
        traversal(root->right, vec);
        vec.push_back(root->val);
    }
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> result;
        traversal(root, result);
        return result;

    }
};

先中右左遍历,然后再反转

class Solution {
public:

    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> result;
        st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            st.pop();
            if (node != NULL) result.push_back(node->val);
            else continue;
            st.push(node->left); // 相对于前序遍历,这更改一下入栈顺序
            st.push(node->right);
        }
        reverse(result.begin(), result.end()); // 将结果反转之后就是左右中的顺序了
        return result;
    }
};

栈 通用模板

详细代码注释看 0094.二叉树的中序遍历

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != NULL) {
                st.pop();
                st.push(node);                          // 中
                st.push(NULL);

                if (node->right) st.push(node->right);  // 右
                if (node->left) st.push(node->left);    // 左

            } else {
                st.pop();
                node = st.top();
                st.pop();
                result.push_back(node->val);
            }
        }
        return result;
    }
};

更多算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。