-
Notifications
You must be signed in to change notification settings - Fork 0
/
GFG Boundary Traversal of binary tree.java
42 lines (40 loc) · 1.32 KB
/
GFG Boundary Traversal 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
// class Node
// {
// int data;
// Node left, right;
// public Node(int d)
// {
// data = d;
// left = right = null;
// }
// }
class Solution
{
ArrayList<Integer> boundary(Node node)
{
ArrayList<Integer> left = new ArrayList<>();
if (node == null) return left;
if (node.left != node.right) left.add(node.data);
if (node.left != null) travelLeft(node.left, left);
travel(node, left);
if (node.right != null) travelRight(node.right, left, left.size());
return left;
}
static void travelLeft(Node cur, List<Integer> left) {
if (cur.left != cur.right) left.add(cur.data);
if (cur.left != null) travelLeft(cur.left, left);
else if (cur.right != null) travelLeft(cur.right, left);
}
static void travel(Node root, List<Integer> leaf) {
if (root == null) return;
if (root.left == null && root.right == null)
leaf.add(root.data);
travel(root.left, leaf);
travel(root.right, leaf);
}
static void travelRight(Node cur, List<Integer> right, int index) {
if (cur.left != cur.right) right.add(index, cur.data);
if (cur.right != null) travelRight(cur.right, right, index);
else if (cur.left != null) travelRight(cur.left, right, index);
}
}