生活随笔
收集整理的這篇文章主要介紹了
常考数据结构与算法-morris遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下圖右邊就是左邊的樹的morris序
只要一個節點有左樹,該節點一定會到達兩次.
后序
public class Code_MorrisTraversal {public static class Node{public int value
;Node left
;Node right
;public Node(int data
){this.value
= data
;}}public static void main(String[] args
) {Node head
= new Node(4);head
.left
= new Node(2);head
.right
= new Node(6);head
.left
.left
= new Node(1);head
.left
.right
= new Node(3);head
.right
.left
= new Node(5);head
.right
.right
= new Node(7);morrisPre(head
);morrisIn(head
);morrisPos(head
);}public static void process(Node node
){if(null == node
){return;}process(node
.left
);process(node
.right
);}public static void morris(Node head
){if(null == head
){return;}Node cur
= head
;Node mostRight
= null;while(cur
!= null){mostRight
= cur
.left
;if(null != mostRight
){while (null != mostRight
.right
&& mostRight
.right
!= cur
){mostRight
= mostRight
.right
;}if(null == mostRight
.right
){mostRight
.right
= cur
;cur
= cur
.left
;continue;}else{mostRight
.right
= null;}}cur
= cur
.right
;}}public static void morrisPre(Node head
){if(null == head
){return;}Node cur
= head
;Node mostRight
= null;while(cur
!= null){mostRight
= cur
.left
;if(null != mostRight
){while (null != mostRight
.right
&& mostRight
.right
!= cur
){mostRight
= mostRight
.right
;}if(null == mostRight
.right
){System.out
.println(cur
.value
); mostRight
.right
= cur
;cur
= cur
.left
;continue;}else{mostRight
.right
= null;}}else{System.out
.println(cur
.value
);}cur
= cur
.right
;}}public static void morrisIn(Node head
){if(null == head
){return;}Node cur
= head
;Node mostRight
= null;while(cur
!= null){mostRight
= cur
.left
;if(null != mostRight
){while (null != mostRight
.right
&& mostRight
.right
!= cur
){mostRight
= mostRight
.right
;}if(null == mostRight
.right
){mostRight
.right
= cur
;cur
= cur
.left
;continue;}else{mostRight
.right
= null;}}System.out
.println(cur
.value
);cur
= cur
.right
;}}public static void morrisPos(Node head
){if(null == head
){return;}Node cur
= head
;Node mostRight
= null;while(cur
!= null){mostRight
= cur
.left
;if(null != mostRight
){while (null != mostRight
.right
&& mostRight
.right
!= cur
){mostRight
= mostRight
.right
;}if(null == mostRight
.right
){mostRight
.right
= cur
;cur
= cur
.left
;continue;}else{mostRight
.right
= null;printEdge(cur
.left
); }}cur
= cur
.right
;}printEdge(head
); }public static void printEdge(Node node
){Node tail
= reverseEdge(node
);Node cur
= tail
;while(null != cur
){System.out
.println(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
;}
}
總結
以上是生活随笔為你收集整理的常考数据结构与算法-morris遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。