|
| 1 | +/** |
| 2 | + * |
| 3 | + * @author Varun Upadhyay (https://github.com/varunu28) |
| 4 | + * |
| 5 | + */ |
| 6 | +import java.util.LinkedList; |
| 7 | + |
| 8 | +public class FindHeightOfTree { |
| 9 | + |
| 10 | + // Driver Program |
| 11 | + public static void main(String[] args) { |
| 12 | + Node tree = new Node(5); |
| 13 | + tree.insert(3); |
| 14 | + tree.insert(7); |
| 15 | + tree.insert(1); |
| 16 | + tree.insert(-1); |
| 17 | + tree.insert(29); |
| 18 | + tree.insert(93); |
| 19 | + tree.insert(6); |
| 20 | + tree.insert(0); |
| 21 | + tree.insert(-5); |
| 22 | + tree.insert(-6); |
| 23 | + tree.insert(-8); |
| 24 | + tree.insert(-1); |
| 25 | + |
| 26 | + // A level order representation of the tree |
| 27 | + tree.printLevelOrder(); |
| 28 | + System.out.println(); |
| 29 | + |
| 30 | + System.out.println("Height of the tree is: " + tree.findHeight()); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * The Node class which initializes a Node of a tree |
| 36 | + * printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc |
| 37 | + * findHeight: Returns the height of the tree i.e. the number of links between root and farthest leaf |
| 38 | + */ |
| 39 | +class Node { |
| 40 | + Node left, right; |
| 41 | + int data; |
| 42 | + |
| 43 | + public Node(int data) { |
| 44 | + this.data = data; |
| 45 | + } |
| 46 | + |
| 47 | + public void insert (int value) { |
| 48 | + if (value < data) { |
| 49 | + if (left == null) { |
| 50 | + left = new Node(value); |
| 51 | + } |
| 52 | + else { |
| 53 | + left.insert(value); |
| 54 | + } |
| 55 | + } |
| 56 | + else { |
| 57 | + if (right == null) { |
| 58 | + right = new Node(value); |
| 59 | + } |
| 60 | + else { |
| 61 | + right.insert(value); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + public void printLevelOrder() { |
| 67 | + LinkedList<Node> queue = new LinkedList<>(); |
| 68 | + queue.add(this); |
| 69 | + while(!queue.isEmpty()) { |
| 70 | + Node n = queue.poll(); |
| 71 | + System.out.print(n.data + " "); |
| 72 | + if (n.left != null) { |
| 73 | + queue.add(n.left); |
| 74 | + } |
| 75 | + if (n.right != null) { |
| 76 | + queue.add(n.right); |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + public int findHeight() { |
| 82 | + return findHeight(this); |
| 83 | + } |
| 84 | + |
| 85 | + private int findHeight(Node root) { |
| 86 | + if (root.left == null && root.right == null) { |
| 87 | + return 0; |
| 88 | + } |
| 89 | + else if (root.left != null && root.right != null) { |
| 90 | + return 1 + Math.max(findHeight(root.left), findHeight(root.right)); |
| 91 | + } |
| 92 | + else if (root.left == null && root.right != null) { |
| 93 | + return 1 + findHeight(root.right); |
| 94 | + } |
| 95 | + else { |
| 96 | + return 1 + findHeight(root.left); |
| 97 | + } |
| 98 | + } |
| 99 | +} |
| 100 | + |
0 commit comments