145. 二叉樹的後序遍歷

簡單 深度優先搜索 二叉樹

思路

前序遍歷是按照[左,右,中]的順序去輸出的,
也就是先輸出中間的節點,再輸出左樹的節點,最後右樹的節點。
以右圖為例,輸出的順序就是 [1,2,4,5,3,7][1,2,4,5,3,7]
一開始中間節點是 11 ,左樹是 [2,4,5][2,4,5] ,右樹是 [3,7][3,7]
這能用先序遍歷的變形去取得。

圖片

在先序遍歷時,我們按照[中,左,右]的順序去輸出,為了先左再右,使用棧去反轉。
既然會[中,左,右],那麼[中,右,左]也就呼之欲出了。
此時再把[中,右,左]整個倒轉過來,就得到後序遍歷目標的[左,右,中]了。

程式碼

1. 用 stack 倒轉

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if(!root) return {};
        vector<int> res;
        stack<TreeNode*> stk;
        stack<int> collected;
        stk.push(root);
        while(!stk.empty()) {
            TreeNode* cur = stk.top(); stk.pop();
            collected.push(cur->val); // 中
            if(cur->left) stk.push(cur->left); // 左
            if(cur->right) stk.push(cur->right); // 右
        }
        while(!collected.empty()) {
            res.push_back(collected.top());
            collected.pop();
        }
        return res;
    }
};
/*
中右左 -> 左右中
*/

2. STL 直接倒轉

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if(!root) return {};
        vector<int> res;
        stack<TreeNode*> stk;
        stk.push(root);
        while(!stk.empty()) {
            TreeNode* cur = stk.top(); stk.pop();
            res.push_back(cur->val); // 中
            if(cur->left) stk.push(cur->left); // 左
            if(cur->right) stk.push(cur->right); // 右
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

3. 遞迴

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

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)

顯示設定

背景線條
顯示背景網格線條
懸停發光
滑鼠懸停時顯示霓虹效果
聚光燈
跟隨滑鼠的聚光燈效果
背景透明度
開啟透明玻璃效果
主題顏色
自訂主要顏色