-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBoundaryTraversal.java
65 lines (55 loc) · 2.01 KB
/
BoundaryTraversal.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
package main.java.topcodingquestion.treesandgraphs;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class BoundaryTraversal {
LinkedList<Integer> boundaryElement = new LinkedList<>();
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
if (root == null) return new ArrayList<>();
boundaryElement.add(root.val);
//add left boundary elements(except leaf node)
leftBoundary(root.left);
// add leaf nodes
if (!isLeaf(root)) {
leafNodes(root);
}
//add right boundary(except leaf node)
rightBoundary(root.right);
return boundaryElement;
}
// Recursive function to print the left boundary of the given binary tree
// in a top-down fashion, except for the leaf nodes
private void leftBoundary(TreeNode root) {
TreeNode node = root;
while (node != null && !isLeaf(node)) {
boundaryElement.addLast(node.val);
// next process, the left child of `root` if it exists;
// otherwise, move to the right child
node = (node.left != null) ? node.left : node.right;
}
}
// Recursive function to print the leaf nodes of the given
// binary tree in an inorder fashion
private void leafNodes(TreeNode root) {
//base case
if (root == null)
return;
leafNodes(root.left);
if (isLeaf(root)) {
boundaryElement.addLast(root.val);
}
leafNodes(root.right);
}
// Recursive function to print the right boundary of the given binary tree
// in a bottom-up fashion, except for the leaf nodes
private void rightBoundary(TreeNode root) {
if (root == null || isLeaf(root)) {
return;
}
rightBoundary(root.right != null ? root.right : root.left);
boundaryElement.addLast(root.val);
}
private boolean isLeaf(TreeNode node) {
return node != null && node.left == null && node.right == null;
}
}