给出一棵二叉树,返回其中序遍历
样例
给出二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,3,2]
.
挑战
你能使用非递归算法来实现么?
递归
vector<int> a;
vector<int> inorderTraversal(TreeNode * root) {
// write your code here
if(root==NULL){return a;}
else{
inorderTraversal(root->left);
a.push_back(root->val);
inorderTraversal(root->right);
}
return a;
}
非递归
vector<int> inorderTraversal(TreeNode * root) {
// write your code here
vector<int> a;
int top=-1;
TreeNode * s[100];
while(root!=NULL || top!=-1){
while(root!=NULL){
s[++top]=root;
root=root->left;
}
if(top!=-1){
root = s[top--];
a.push_back(root->val);
root=root->right;
}
}
return a;
}