Leetcode實戰: 94. 二叉樹的中序遍歷

題目

給定一個二叉樹,返回它的中序 遍歷。

示例

在這裏插入圖片描述

進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?

算法實現:遞歸

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        return dfs(root, res);
    }
    vector<int> dfs(TreeNode* root, vector<int> res) {
        if (!root) return res;
        res = dfs(root->left, res);
        res.push_back(root->val);
        res = dfs(root->right, res);
        return res;
    }
};

結果

在這裏插入圖片描述

算法實現:迭代

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> sta;
        while (!sta.empty() || root) {
            while (root) {
                sta.push(root);
                root = root->left;
            }
            root = sta.top();
            sta.pop();
            res.push_back(root->val);
            root = root->right;
        }
        return res;
    }
    
};

結果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章