非递归算法:利用栈来实现
/**
- 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:
vectorans;
stack<TreeNode>s;
TreeNode p;
vector inorderTraversal(TreeNode root) {
if(root==NULL) return ans;
p=root;
while(!s.empty()||p!=NULL){
while(p!=NULL){//左孩子入栈
s.push§;
p=p->left;
}
if(!s.empty()){
p=s.top();
s.pop();
ans.push_back(p->val);
p=p->right;
}
}
return ans;
}
};
递归算法:
/** - 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:
vectorans;
vector inorderTraversal(TreeNode root) {
if(root==NULL) return ans;
inorderTraversal( root->left);
ans.push_back(root->val);
inorderTraversal(root->right);
return ans;
}
};