程式語言 - LeetCode - C++ - 94. Binary Tree Inorder Traversal



題目:


解答一(DFS):

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> ans;

        auto inorder = [&](this auto&& inorder, TreeNode* root) -> void {
            if (!root) {
                return;
            }

            inorder(root->left);
            ans.push_back(root->val);
            inorder(root->right);
        };

        inorder(root);
        return ans;
    }
};

解答二(BFS):

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> ans;
        stack<TreeNode*> q;

        while (root || !q.empty()) {
            while (root) {
                q.push(root);
                root = root->left;
            }

            root = q.top();
            q.pop();
            ans.push_back(root->val);

            root = root ->right;
        }

        return ans;
    }
};