1. 程式人生 > 實用技巧 >LeetCode94二叉樹中序遍歷

LeetCode94二叉樹中序遍歷

題目連結

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

題解一:遞迴

// Problem: LeetCode 94
// URL: https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
// Tags: Tree Recursion Stack
// Difficulty: Medium

#include <iostream>
#include <vector>
using namespace std;

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):val(x), left(nullptr), right(nullptr){}
};

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

    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        traversal(root, result);
        return result;
    }
};

int main()
{
    cout << "helloworld" << endl;
    // system("pause");
    return 0;
}

題解二:非遞迴(通過棧模擬遞迴)

思路:https://www.cnblogs.com/chouxianyu/p/13293284.html

// Problem: LeetCode 94
// URL: https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
// Tags: Tree Recursion Stack
// Difficulty: Medium

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):val(x), left(nullptr), right(nullptr){}
};

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> nodes;
        if(root!=nullptr)
            nodes.push(root);
        while(!nodes.empty()){
            root = nodes.top();
            nodes.pop();
            // 模擬呼叫遞迴函式
            if(root!=nullptr){
                if(root->right!=nullptr)
                    nodes.push(root->right);
                nodes.push(root);
                nodes.push(nullptr);
                if(root->left!=nullptr)
                    nodes.push(root->left);
            }
            // 一層遞迴函式結束
            else{
                result.push_back(nodes.top()->val);
                nodes.pop();
            }
        }
        return result;
    }
};

int main()
{
    cout << "helloworld" << endl;
    // system("pause");
    return 0;
}

作者:@臭鹹魚

轉載請註明出處:https://www.cnblogs.com/chouxianyu/

歡迎討論和交流!