Pseduo Logic -Height of a binary tree is to return Max of height of left subtree and right subtree + 1
/*
The height of a node is the number of edges on the longest path from the node to a leaf.
A leaf node will have a height of 0.
*/
public class HeightBinaryTree {
public static void main(String[] args) {
BinarySearch bs = new BinarySearch();
bs.insertNode(15);
bs.insertNode(10);
bs.insertNode(20);
bs.insertNode(5);
bs.insertNode(25);
bs.insertNode(3);
HeightBinaryTree hbt= new HeightBinaryTree();
int height =hbt.heightBinaryTree(bs.root);
System.out.println("Height of binary tree is "+ height);
}
public int heightBinaryTree(Node node){
if(node==null)
return 0;
int leftHeight=heightBinaryTree(node.leftChild);
int rightHeight=heightBinaryTree(node.rightChild);
return Math.max(leftHeight, rightHeight)+1;
}
}
Output:
Height of binary tree is 4
No comments:
Post a Comment