给定一棵二叉树的头节点 head,完成二叉树的先序、中序和后序遍历。
如果二叉树的节点数为 N,要求时间复杂度为 O(N),额外空间复杂度为 O(1)
如果二叉树的节点数为 N,要求时间复杂度为 O(N),额外空间复杂度为 O(1)
主要思想:莫尔斯遍历,使用空闲右指针,回到后续节点,只需要关心一个节点的左子树的最右节点是悬空还是指向后续节点
public static class Node{
public int value;
Node left;
Node right;
public Node(int data){
this.value = data;
}
}
public static void morrisIn(Node head){
if(head == null){
return;
}
Node cur1 = head;
Node cur2 = null;
while(cur1 != null){
cur2 = cur1.left;
if(cur2 != null){
while(cur2.right != null && cur2.right != cur1){
cur2 = cur2.right;
}
if(cur2.right == null){
cur2.right = cur1;
cur1 = cur1.left;
continue;
}else{
cur2.right = null;
}
}
System.out.print(cur1.value + " ");
cur1 = cur1.right;
}
System.out.println();
}
public static void morrisPre(Node head){
if(head == null){
return;
}
Node cur1 = head;
Node cur2 = null;
while(cur != null){
cur2 = cur1.left;
if(cur2 != null){
while(cur2.right != null && cur2.right != cur1){
cur2 = cur2.right;
}
if(cur2.right == null){
cur2.right = cur1;
System.out.print(cur1.value + " ");
cur1 = cur1.left;
continue;
}else{
cur2.right = null;
}
}else{
System.out.print(cur1.value + " ");
}
cur1 = cur1.right;
}
System.out.println();
}
public static void morrisPos(Node head){
if(head == null){
return;
}
Node cur1 = head;
Node cur2 = null;
while(cur1 != null){
if(cur2 != null){
while(cur2.right != null && cur2.right != cur1){
cur2 = cur2.right;
}
if(cur2.right == null){
cur2.right = cur1;
cur1 = cur1.left;
continue;
}else{
cur2.right = null;
printEdge(cur1.left);
}
}
cur1 = cur1.right;
}
printEdge(head);
System.out.println();
}
public static void printEdge(Node head){
Node tail = reverseEdge(head);
Node cur = tail;
while(cur != null){
System.out.print(cur.value + " ");
cur = cur.right;
}
reverseEdge(tail);
}
public static Node reverseEdge(Node from){
Node pre = null;
Node next = null;
while(from != null){
next = from.right;
from.right = pre;
pre = from;
from = next;
}
return pre;
}