-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBoundaryTreeTraversal.java
More file actions
60 lines (54 loc) · 1.63 KB
/
BoundaryTreeTraversal.java
File metadata and controls
60 lines (54 loc) · 1.63 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
import java.util.*;
public class BoundaryTreeTraversal {
public boolean isLeaf(TreeNode node) {
if (node.left == null && node.right == null)
return true;
return false;
}
public void addLeftBoundary(TreeNode root, List<Integer> res) {
TreeNode cur = root.left;
while (cur != null) {
if (isLeaf(cur) == false)
res.add(cur.val);
if (cur.left != null)
cur = cur.left;
else
cur = cur.right;
}
}
public void addLeaves(TreeNode root, List<Integer> res) {
if (isLeaf(root)) {
res.add(root.val);
return;
}
if (root.left != null)
addLeaves(root.left, res);
if (root.right != null)
addLeaves(root.right, res);
}
public void addRightBoundary(TreeNode root, List<Integer> res) {
List<Integer> temp = new ArrayList<>();
TreeNode cur = root.right;
while (cur != null) {
if (isLeaf(cur) == false)
temp.add(cur.val);
if (cur.right != null)
cur = cur.right;
else
cur = cur.left;
}
for (int i = temp.size() - 1; i >= 0; i--)
res.add(temp.get(i));
}
public List<Integer> printBounday(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null)
return res;
if (isLeaf(root) == false)
res.add(root.val);
addLeftBoundary(root, res);
addLeaves(root, res);
addRightBoundary(root, res);
return res;
}
}