用到了前驱节点!就是使用前驱节点,来判断当前节点有没有被访问过!
1. 当前驱节点的右节点为null,说明此时第一次访问当前节点,不应该输出,此时将前驱节点指向 当前节点;(因为输出为 左 - 中 - 右,所以右节点作为前驱节点)
2. 前驱节点的 右节点指向 当前节点,说明第二次遍历,需要输出!同时重新将 前驱节点右节点置空!
代码:理解,将时间复杂度降为 O(1),省去了栈的创建!
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
TreeNode pre = null;//前驱节点
while(root != null){
if(root.left != null){
//cur不能动,会丢失位置
pre = root.left;
while(pre.right != null && pre.right != root){
pre = pre.right;
}
//找到了前驱节点
if(pre.right == null){
pre.right = root;
//要往下走
root = root.left;
}else{
res.add(root.val);
pre.right = null;//重新置空
//往下走
root = root.right;
}
}
//说明左子树输出结束,输出当前节点
else{
res.add(root.val);
root = root.right;//输出了当前节点,需要输出右子树!
}
}
return res;
}
}
最后挪到了 root的right怎么理解,如果为空,循环就结束了,剩下的节点怎么输出!
懂了!!!
此时root.right 都被加上了一个节点,不再为null,Morris,将其变成了一个前驱节点,此时回去执行上一层的节点!
只要不是右边点,都会有下一个节点!!!