思路:二叉树的中序遍历为:左-中-右。递归调用即可,代码如下。
/**
* 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> inorderTraversal(TreeNode* root) {
vector<int> ans;
inorder(root,ans);
return ans;
}
void inorder(TreeNode* root,vector<int> &ans)
{
if(!root) return;
if(root->left) inorder(root->left,ans);
ans.push_back(root->val);
if(root->right) inorder(root->right,ans);
}
};