|
| 1 | +package binaryTrees1; |
| 2 | + |
| 3 | +public class BinaryTreeUse { |
| 4 | + |
| 5 | + /* Root -> Left -> Right: Traversal on Binary Tree */ |
| 6 | + public static void printBinaryTree(BinaryTreeNode<Integer> root) { |
| 7 | +// Base Case: if the root is null we just return from that position without doing anything |
| 8 | + if (root == null) return; |
| 9 | + System.out.println(root.data); |
| 10 | + printBinaryTree(root.left); |
| 11 | + printBinaryTree(root.right); |
| 12 | + } |
| 13 | + |
| 14 | + /* Root -> Left -> Right: Traversal on Binary Tree */ |
| 15 | + public static void printBinaryTreeDetailed(BinaryTreeNode<Integer> root) { |
| 16 | +// Base Case: if the root is null we just return from that position without doing anything |
| 17 | + if (root == null) return; |
| 18 | +// At this point we only know root is not null |
| 19 | + System.out.print(root.data + " : "); |
| 20 | +// Printing for the root's left & right data |
| 21 | + if (root.left != null) System.out.print("Left -> " + root.left.data + ", "); |
| 22 | + if (root.right != null) System.out.print("Right -> " + root.right.data); |
| 23 | + System.out.println(); |
| 24 | +// Now, calling recursively on root's left and root's right |
| 25 | + printBinaryTreeDetailed(root.left); |
| 26 | + printBinaryTreeDetailed(root.right); |
| 27 | + } |
| 28 | + |
| 29 | + public static void main(String[] args) { |
| 30 | +// Creating the nodes |
| 31 | + var root = new BinaryTreeNode<Integer>(1); |
| 32 | + |
| 33 | + var rootLeft = new BinaryTreeNode<Integer>(2); |
| 34 | + var rootRight = new BinaryTreeNode<Integer>(3); |
| 35 | +// connecting the nodes |
| 36 | + root.left = rootLeft; |
| 37 | + root.right = rootRight; |
| 38 | +// first part of tree created |
| 39 | + |
| 40 | +// second part is creating |
| 41 | + var twoRight = new BinaryTreeNode<Integer>(4); |
| 42 | + var threeLeft = new BinaryTreeNode<Integer>(5); |
| 43 | + |
| 44 | + rootLeft.right = twoRight; |
| 45 | + rootRight.left = threeLeft; |
| 46 | + |
| 47 | + printBinaryTreeDetailed(root); |
| 48 | + } |
| 49 | +} |
0 commit comments