-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBoundary of Binary Tree.java
56 lines (48 loc) · 1.5 KB
/
Boundary of Binary Tree.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<Integer> res;
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
// Check left boundary, leaves and right boundary
res = new ArrayList<>();
if(root == null) return res;
res.add(root.val);
leftBound(root.left);
leaf(root.left);
leaf(root.right);
rightBound(root.right);
return res;
}
private void leftBound(TreeNode node) {
// Top down for anti-clockwise
if(node == null || isLeaf(node)) return;
res.add(node.val);
if(node.left != null) leftBound(node.left);
else leftBound(node.right);
}
private void rightBound(TreeNode node) {
// Bottom up for anti-clockwise
if(node == null || isLeaf(node)) return;
if(node.right != null) rightBound(node.right);
else rightBound(node.left);
res.add(node.val);
}
private void leaf(TreeNode node) {
if(node == null) return;
if(isLeaf(node)) res.add(node.val);
else {
leaf(node.left);
leaf(node.right);
}
}
private boolean isLeaf(TreeNode node) {
return node.left == null && node.right == null;
}
}