-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundaryTraversal.java
More file actions
61 lines (50 loc) · 1.54 KB
/
BoundaryTraversal.java
File metadata and controls
61 lines (50 loc) · 1.54 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
61
package Trees;
public class BoundaryTraversal {
static void printLeftBoundary(Node root) {
if (root == null) return;
if (root.left != null || root.right != null) {
System.out.print(root.val + " ");
}
if (root.left != null) {
printLeftBoundary(root.left);
} else {
printLeftBoundary(root.right);
}
}
// Function to print the right boundary nodes of a binary tree.
static void printRightBoundary(Node root) {
if (root == null) return;
if (root.right != null) {
printRightBoundary(root.right);
} else {
printRightBoundary(root.left);
}
if (root.left != null || root.right != null) {
System.out.print(root.val + " ");
}
}
// Function to print the leaves of a binary tree.
static void printLeaves(Node root) {
if (root == null) {
return;
}
printLeaves(root.left);
if (root.left == null && root.right == null) {
System.out.print(root.val + " ");
}
printLeaves(root.right);
}
// Function to print the boundary nodes of a binary tree in anticlockwise order.
static void printBoundary(Node root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
printLeftBoundary(root.left);
printLeaves(root.left);
printLeaves(root.right);
printRightBoundary(root.right);
}
public static void main(String[] args) {
}
}