-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBTInorderTraversal.java
More file actions
75 lines (62 loc) · 1.13 KB
/
BTInorderTraversal.java
File metadata and controls
75 lines (62 loc) · 1.13 KB
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
import java.util.*;
public class BTInorderTraversal {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ret = new LinkedList<Integer>();
TreeNode iter = root;
if(iter.left!= null)
{
iter = ToVeryLeft(iter);
ret.add(iter.val);
}
while(iter!= null)
{
iter = GoUp(iter);
if(iter!= null)
{
ret.add(iter.val);
}
if(iter.right!= null)
{
iter = iter.right;
}
if(iter.left!= null)
{
iter = ToVeryLeft(iter);
ret.add(iter.val);
}
}
return ret;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode parent;
TreeNode(int x) { val = x; }
}
public TreeNode ToVeryLeft(TreeNode root)
{
TreeNode temp = root;
while(temp.left!= null)
{
temp = temp.left;
}
return temp;
}
public TreeNode GoUp(TreeNode root)
{
TreeNode temp = root;
while(temp.parent!= null && temp == temp.parent.right)
{
temp = temp.parent;
}
temp = temp.parent;
return temp;
}
}