题目:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
代码:
/**
* 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> ret;
if ( !root ) return ret;
stack<TreeNode*> sta;
sta.push(root);
while ( !sta.empty() )
{
TreeNode *tmp = sta.top();
sta.pop();
if ( tmp->right ) sta.push(tmp->right);
if ( tmp->left ){
TreeNode *tmp_left = tmp->left;
tmp->left = NULL;
tmp->right = NULL;
sta.push(tmp);
sta.push(tmp_left);
}
else{
ret.push_back(tmp->val);
}
}
return ret;
}
};
tips:
跟先序遍历类似:人工构建一个stack
1. 每次栈顶元素出栈
2. 判断tmp->right是否压入
3. 如果tmp->left不为空:则把左节点保存下来;把tmp节点right left置为空(剪出来这个tmp点),入栈;左节点再入栈
如果tmp->left为空:证明没有left了,直接将tmp->val加入到ret中
====================================
上面的代码略微有些山寨,学习了一个比较consice的代码,自己写了一遍AC如下:
代码:
/**
* 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> ret;
stack<TreeNode *> sta;
TreeNode *p = root;
while ( !sta.empty() || p )
{
if ( p )
{
sta.push(p);
p = p->left;
}
else
{
p = sta.top();
sta.pop();
ret.push_back(p->val);
p = p->right;
}
}
return ret;
}
};
tips:
维护一个指针p,指向当前要处理的TreeNode:
1. 如果p不为空,则p入栈,p=p->left即p往左边走
2. 如果p为空了,但是堆栈不为空,则证明继续往left方向走不通了,可以往右走了;从栈中弹出一个元素,将其值推入ret ,并继续右走(令p = p->right)
=========================================
第二次过这道题,感觉用递归的比较好写,不用递归的难度大一些,强迫不用递归。
/**
* 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> ret;
stack<TreeNode*> sta;
TreeNode* curr = root;
while ( !sta.empty() || curr )
{
if ( curr )
{
sta.push(curr);
curr = curr->left;
}
else
{
curr = sta.top();
sta.pop();
ret.push_back(curr->val);
curr = curr->right;
}
}
return ret;
}
};