递归、栈遍历二叉树都是O(n)空间复杂度,莫里斯的方法只需O(1)空间复杂度
伪代码:
初始化当前节点为root
while 当前节点不为空
if 当前节点没有左孩子
输出当前节点的值
前往右孩子 ( 即cur = cur.right )
else (即当前节点有左孩子时)
把当前节点作为 当前节点左子树的最右端节点的 右孩子 (如下图的虚线)
前往当前节点的左孩子 (即 cur = cur.left )
JAVA 版本代码
public void moris(TreeNode root){
TreeNode cur = root;
TreeNode pre = null;
if (cur.left == null){
System.out.println(cur.val);
cur = cur.right;
}else { // 即当前节点有左孩子时
// 记录前驱节点
pre = cur.left;
// 找到当前节点左子树的最右端节点
while (pre.right != null && pre.right != cur){
pre = pre.right;
}
// 找到最右端节点
if (pre.right == null){
// 把当前节点作为 当前节点左子树的最右端节点的 右孩子
pre.right = cur;
cur = cur.left;
}else {
// 将右孩子置为null, 即去掉图中虚线
pre.right = null;
System.out.println(cur.val);
cur = cur.right;
}
}
}