链接
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
耗时
解题:18 min
题解:1 min
题意
给定一个二叉树,返回它的中序 遍历。
思路
详见代码。
时间复杂度: O ( n ) O(n) O(n)
AC代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> ans;
void dfs(TreeNode* root) {
if(root == NULL) return ;
dfs(root->left);
ans.push_back(root->val);
dfs(root->right);
}
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return ans;
}
};