LeetCode HOT100 - 二叉树的中序遍历

简单搜索

左中右

/**
 * 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 dfs = [&](this auto&& self, TreeNode* x) -> void {
            if (!x) {
                return;
            }
            self(x->left);
            ans.emplace_back(x->val);
            self(x->right);
        };
        dfs(root);
        return ans;
    }
};
posted @ 2026-05-07 23:16  rdcamelot  阅读(19)  评论(0)    收藏  举报