方法一:递归
/**
* 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) {
return inOrder(root);
}
vector<int> inOrder(TreeNode* root){
vector<int> result,temp;
if(root==nullptr) return result;
// 左边
if(root->left!=nullptr){
temp=inOrder(root->left);
result.insert(result.end(),temp.begin(),temp.end());
}
// 中间
result.push_back(root->val);
// 右边
if(root->right!=nullptr){
temp=inOrder(root->right);
result.insert(result.end(),temp.begin(),temp.end());
}
return result;
}
};
方法二:栈
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> S;
TreeNode* p=root;
vector<int> result;
while(p!=nullptr || !S.empty()){
if(p!=nullptr){
S.push(p);
p=p->left;
}
else{
p=S.top();
S.pop();
result.push_back(p->val);
p=p->right;
}
}
return result;
}
};