public class PrintBoundryOftree {
public static void main(String[] args) {
int[] arr = {10, 5, 4, 7, 15, 14, 17};
Node root = null;
for (int val : arr) {
root = insertNode(root, val);
}
printInorder(root);
System.out.println("\n*** print boundry***\n");
System.out.println("**print left**");
printLeftBoundry(root);
System.out.println("\n**print right boundry**\n");
printRightBoundry(root.right); //start from right due to root already cover in left boundry
System.out.println("\n**leaf boundry**\n");
printLeafBoundry(root);
}
static void printLeftBoundry(Node node) {
if (null != node) {
if (null != node.left) {
System.out.println(node.value);
printLeftBoundry(node.left);
} else if (null != node.right) {
System.out.println(node.value);
printLeftBoundry(node.right);
}
}
}
static void printRightBoundry(Node node) {
if (null != node) {
if (null != node.right) {
System.out.println(node.value);
printRightBoundry(node.right);
} else if (null != node.left) {
System.out.println(node.value);
printRightBoundry(node.left);
}
}
}
static void printLeafBoundry(Node node) {
if (null != node) {
printLeafBoundry(node.left);
if (null == node.left && null == node.right) {
System.out.println(node.value);
}
printLeafBoundry(node.right);
}
}
static void printInorder(Node root) {
if (null != root) {
printInorder(root.left);
System.out.println(root.value);
printInorder(root.right);
} else {
return;
}
}
static Node insertNode(Node root, Integer value) {
Node newNode = new Node(value);
if (root == null) {
return newNode;
} else {
if (value <= root.value) {
root.left = insertNode(root.left, value);
} else {
root.right = insertNode(root.right, value);
}
return root;
}
}
static class Node {
Integer value;
Node left;
Node right;
Node(Integer value) {
this.value = value;
left = right = null;
}
}
}
output:
**original**
4
5
7
10
14
15
17
*** print boundry***
**print left**
10
5
**print right**
15
**left**
4
7
14
17
Ref: https://www.youtube.com/watch?v=uemjIijtu2I
No comments:
Post a Comment