forked from kexun/sort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MorrisTree.java
103 lines (82 loc) · 1.61 KB
/
MorrisTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.demo;
/**
* morris遍历树,在时间复杂度为O(n),空间复杂度O(1)的前提下,遍历二叉树。
* @author kexun
*
*/
public class MorrisTree {
public static void main(String[] args) {
Tree head = new Tree(1);
Tree h2 = new Tree(2);
Tree h3 = new Tree(3);
Tree h4 = new Tree(4);
Tree h5 = new Tree(5);
Tree h6 = new Tree(6);
Tree h7 = new Tree(7);
Tree h8 = new Tree(8);
Tree h9 = new Tree(9);
Tree h10 = new Tree(10);
head.left = h2;
head.right = h3;
h2.left = h4;
h2.right = h5;
h4.left = h6;
h5.right = h7;
h3.left = h8;
h3.right = h9;
h9.right = h10;
MorrisTree v = new MorrisTree();
// v.morrisInTree(head);
v.morrisPreTree(head);
}
/**
* morris遍历 中序
* @param head
*/
public void morrisInTree(Tree head) {
if (head == null) {
return;
}
Tree c1 = head;
Tree c2 = null;
while (c1 != null) {
c2 = c1.left;
if (c2 != null) {
while (c2.right != null && c2.right != c1) {
c2 = c2.right;
}
if (c2.right == null) {
c2.right = c1;
c1 = c1.left;
continue;
} else {
c2.right = null;
}
}
System.out.println(c1.data);
c1 = c1.right;
}
}
/**
* morris遍历 先序
* @param head
*/
public void morrisPreTree(Tree head) {
if (head == null) {
return;
}
Tree c1 = head;
Tree c2 = null;
while (c1 != null) {
System.out.println(c1.data);
c2 = c1.left;
if (c2 != null) {
while (c2.right != null) {
c2 = c2.right;
}
c2.right = c1.right;
}
c1 = c1.left != null? c1.left : c1.right;
}
}
}