-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
53 lines (51 loc) · 1.52 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
class Solution {
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
List<Integer> ans = new ArrayList<>();
ans.add(root.val);
if (root.left == root.right) {
return ans;
}
List<Integer> left = new ArrayList<>();
List<Integer> leaves = new ArrayList<>();
List<Integer> right = new ArrayList<>();
dfs(left, root.left, 0);
dfs(leaves, root, 1);
dfs(right, root.right, 2);
ans.addAll(left);
ans.addAll(leaves);
Collections.reverse(right);
ans.addAll(right);
return ans;
}
private void dfs(List<Integer> nums, TreeNode root, int i) {
if (root == null) {
return;
}
if (i == 0) {
if (root.left != root.right) {
nums.add(root.val);
if (root.left != null) {
dfs(nums, root.left, i);
} else {
dfs(nums, root.right, i);
}
}
} else if (i == 1) {
if (root.left == root.right) {
nums.add(root.val);
} else {
dfs(nums, root.left, i);
dfs(nums, root.right, i);
}
} else {
if (root.left != root.right) {
nums.add(root.val);
if (root.right != null) {
dfs(nums, root.right, i);
} else {
dfs(nums, root.left, i);
}
}
}
}
}