1.

Write a recursive function to calculate the height of a binary tree in Java.

Answer»
  • Consider that every node of a tree represents a class called Node as given below:
public class Node{
int data;
Node left;
Node right;
}
  • Then the height of the binary tree can be found as follows:
int heightOfBinaryTree(Node node)
{
if (node == null)
return 0; // If node is null then height is 0 for that node.
else
{
// compute the height of each subtree
int leftHeight = heightOfBinaryTree(node.left);
int rightHeight = heightOfBinaryTree(node.right);
//use the larger among the left and right height and plus 1 (for the root)
return Math.max(leftHeight, rightHeight) + 1;
}
}


Discussion

No Comment Found