Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
s思路:
1. 树的问题,就是绕不开遍历。学好遍历,基本树的问题就不成问题了。遍历有两种方式:一种recuesive,一种iterative.这道题要求用iterative.
2. iterative用stack, inorder 和preorder都可以用stack实现,体会下区别。参考http://blog.csdn.net/xinqrs01/article/details/54858782 中preorder的代码,体会区别!
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
//
vector<int> res;
stack ss;
TreeNode* p=root;
while(p||!ss.empty()){
//小bug:常常把!ss.empty()写成ss.empty()。
//这还提醒了我,常常把if(a==0)写成if(a=0),符号写错的问题常发生,应多检查是否笔误
while(p){
ss.push(p);
p=p->left;
}
p=ss.top();
ss.pop();
res.push_back(p->val);
p=p->right;
}
return res;
}
};