Skip to content

Instantly share code, notes, and snippets.

@radhar
Created July 16, 2020 15:14
Show Gist options
  • Save radhar/900ae4445471e09a47e641b97dd88d4e to your computer and use it in GitHub Desktop.
Save radhar/900ae4445471e09a47e641b97dd88d4e to your computer and use it in GitHub Desktop.
Given a binary tree, find the height of the binary tree.
Given a binary tree, find the height of the binary tree.
Expected: Input: Root node of the tree Output: Height of the tree.
public class BinaryTree {
//Represent the node of binary tree
public static class Node{
int data;
Node left;
Node right;
public Node(int data){
//Assigning data to the new node, set left and right children to null
this.data = data;
this.left = null;
this.right = null;
}
}
public Node root;
public BinaryTree(){
root = null;
}
//calculateHeight() will determine the maximum height of the binary tree
public int calculateHeight(Node temp){
//find for tree is empty
if(root == null) {
return 0;
}
else {
int leftHeight = 0, rightHeight = 0;
//Calculate the height of left subtree
if(temp.left != null)
leftHeight = calculateHeight(temp.left);
//Calculate the height of right subtree
if(temp.right != null)
rightHeight = calculateHeight(temp.right);
//Compare height of left subtree and right subtree
//and store maximum of two in variable max
int max = (leftHeight > rightHeight) ? leftHeight : rightHeight;
//Calculate the total height of tree by adding height of root
return (max + 1);
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
//Add nodes to the binary tree
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.right.left = new Node(5);
tree.root.right.right = new Node(6);
tree.root.right.right.right= new Node(7);
tree.root.right.right.right.right = new Node(8);
//Display the maximum height of the given binary tree
System.out.println(tree.calculateHeight(tree.root));
}
}
Output: 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment