题目描述
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]
.
Recursive solution is trivial, could you do it iteratively?
解题思路
题目要求不用递归来实现中序遍历(inorder traversal ),中序就是按[左→中→右]的顺序遍历整棵树。想了想只好使用有先进后出性质的栈了。
任一结点都可能有左子树和右子树。
分两种大情况考虑:
①如果当前结点(栈顶元素)有左子树,那么左子树要入栈,表示优先于当前结点处理(后进先出)。并且把当前结点的左子树指针给置NULL,避免重复访问。
②如果当前结点没有有左子树。这就好处理了。因为当前结点肯定优于右子树输出,所以只需当前结点出栈,并输出其数值。如果当前结点右子树非空,将其压栈进行遍历处理即可。
欢迎评论交流~~
代码
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> sta;
vector<int> res;
if(!root)return res;
sta.push(root);
while(!sta.empty()){
TreeNode* n=sta.top();
if(n->left){
sta.push(n->left);
n->left=NULL;
}else{
sta.pop();
res.push_back(n->val);
if(n->right)
sta.push(n->right);
}
}
return res;
}
};