-
Notifications
You must be signed in to change notification settings - Fork 0
/
BoundaryOfABinaryTree.java
34 lines (31 loc) · 1011 Bytes
/
BoundaryOfABinaryTree.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
List<Integer> nodes = new ArrayList<>(1000);
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
if(root == null) return nodes;
nodes.add(root.val);
leftBoundary(root.left);
leaves(root.left);
leaves(root.right);
rightBoundary(root.right);
return nodes;
}
public void leftBoundary(TreeNode root) {
if(root == null || (root.left == null && root.right == null)) return;
nodes.add(root.val);
if(root.left == null) leftBoundary(root.right);
else leftBoundary(root.left);
}
public void rightBoundary(TreeNode root) {
if(root == null || (root.right == null && root.left == null)) return;
if(root.right == null)rightBoundary(root.left);
else rightBoundary(root.right);
nodes.add(root.val); // add after child visit(reverse)
}
public void leaves(TreeNode root) {
if(root == null) return;
if(root.left == null && root.right == null) {
nodes.add(root.val);
return;
}
leaves(root.left);
leaves(root.right);
}