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?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
解题思路:
不用递归的方法完成二叉树的中序遍历,就让人想到Morris二叉树遍历方法:非递归,空间复杂度O(1),时间复杂度O(N),不用栈...
但是实际上Morris方法遍历二叉树也是采用的时间换空间的做法,用Morris方法,树中的每一个节点要被访问两次,第一次先把中序遍历次序的前一个节点(其实就是节点的左子树的最右结点的右指针)指向当前节点,第二次访问才是真正的访问当前节点。第一遍要完成的工作可以用下表表示:(图片来自网络)
代码:
/**
* Definition for binary tree
* 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;
TreeNode *p=NULL;
while(root){
if(root->left==NULL){//如果左子树为空,访问当前节点,然后向右子树走
ret.push_back(root->val);
root=root->right;
}
else{//左子树非空
p=root->left;
//第一次访问时先走到当前节点的左子树的最右结点
while(p->right&&p->right!=root){
p=p->right;
}
//如果是第一次到达该节点,那么左子树的最右结点肯定是空,把左子树的最右结点的右指针指向当前节点,然后继续向左走
if(p->right==NULL){
p->right=root;
root=root->left;
}
else{//如果左子树的最右结点非空,那么是第二次到达该节点,访问该节点然后向右走
ret.push_back(root->val);
p->right=NULL;
root=root->right;
}
}
}
return ret;
}
};