forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
75 lines (67 loc) · 1.72 KB
/
Solution.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private List<Integer> res;
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
if (root == null) {
return Collections.emptyList();
}
res = new ArrayList<>();
// root
if (!isLeaf(root)) {
res.add(root.val);
}
// left boundary
TreeNode t = root.left;
while (t != null) {
if (!isLeaf(t)) {
res.add(t.val);
}
t = t.left == null ? t.right : t.left;
}
// leaves
addLeaves(root);
// right boundary(reverse order)
Deque<Integer> s = new ArrayDeque<>();
t = root.right;
while (t != null) {
if (!isLeaf(t)) {
s.offer(t.val);
}
t = t.right == null ? t.left : t.right;
}
while (!s.isEmpty()) {
res.add(s.pollLast());
}
// output
return res;
}
private void addLeaves(TreeNode root) {
if (isLeaf(root)) {
res.add(root.val);
return;
}
if (root.left != null) {
addLeaves(root.left);
}
if (root.right != null) {
addLeaves(root.right);
}
}
private boolean isLeaf(TreeNode node) {
return node != null && node.left == null && node.right == null;
}
}