Skip to main content

94.二叉树的中序遍历

::: caution

原题链接:https://leetcode.cn/problems/binary-tree-inorder-traversal/

:::

思路

根据中序遍历的定义使用递归求解。

代码

/**
* 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> res;
void dfs(TreeNode* t) {
if (t) {
dfs(t->left);
res.push_back(t->val);
dfs(t->right);
}
}
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
};