-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathBinaryTreeUse.java
More file actions
51 lines (42 loc) · 1.79 KB
/
BinaryTreeUse.java
File metadata and controls
51 lines (42 loc) · 1.79 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
package binaryTrees1;
import java.util.Scanner;
public class BinaryTreeUse {
/* Root -> Left -> Right: Traversal on Binary Tree */
public static void printBinaryTree(BinaryTreeNode<Integer> root) {
// Base Case: if the root is null we just return from that position without doing anything
if (root == null) return;
System.out.println(root.data);
printBinaryTree(root.left);
printBinaryTree(root.right);
}
/* Root -> Left -> Right: Traversal on Binary Tree */
public static void printBinaryTreeDetailed(BinaryTreeNode<Integer> root) {
// Base Case: if the root is null we just return from that position without doing anything
if (root == null) return;
// At this point we only know root is not null
System.out.print(root.data + " : ");
// Printing for the root's left & right data
if (root.left != null) System.out.print("Left -> " + root.left.data + ", ");
if (root.right != null) System.out.print("Right -> " + root.right.data);
System.out.println();
// Now, calling recursively on root's left and root's right
printBinaryTreeDetailed(root.left);
printBinaryTreeDetailed(root.right);
}
public static void main(String[] args) {
// Creating the nodes
var root = new BinaryTreeNode<>(1);
var rootLeft = new BinaryTreeNode<>(2);
var rootRight = new BinaryTreeNode<>(3);
// connecting the nodes
root.left = rootLeft;
root.right = rootRight;
// first part of tree created
// second part is creating
var twoRight = new BinaryTreeNode<>(4);
var threeLeft = new BinaryTreeNode<>(5);
rootLeft.right = twoRight;
rootRight.left = threeLeft;
printBinaryTreeDetailed(root);
}
}