forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundary of Binary Tree.java
More file actions
60 lines (57 loc) · 1.38 KB
/
Boundary of Binary Tree.java
File metadata and controls
60 lines (57 loc) · 1.38 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list;
List<Integer> rightVal;
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
list = new ArrayList<>();
rightVal = new ArrayList<>();
if (root == null) {
return list;
}
if (root.left == null && root.right == null) {
list.add(root.val);
return list;
}
list.add(root.val);
addLeft(root.left);
addLeaves(root);
addRight(root.right);
for (int i = rightVal.size() - 1; i >= 0; i--) {
list.add(rightVal.get(i));
}
return list;
}
private void addLeft(TreeNode left) {
if (left == null || (left.left == null && left.right == null)) {
return;
}
list.add(left.val);
addLeft(left.left == null ? left.right : left.left);
}
private void addLeaves(TreeNode root) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
list.add(root.val);
return;
}
addLeaves(root.left);
addLeaves(root.right);
}
private void addRight(TreeNode right) {
if (right == null || (right.left == null && right.right == null)) {
return;
}
rightVal.add(right.val);
addRight(right.right == null ? right.left : right.right);
}
}