4. Diameter of Binary tree
4. Diameter of Binary tree
Problem link :- click here
package Binary_Tree;
public class BinaryTree__4
{
static int diameter = Integer.MIN_VALUE;
static int heightOfTree(Node root)
{
if(root == null)
return 0;
int left_height = heightOfTree(root.left);
int right_height = heightOfTree(root.right);
diameter = Math.max(diameter, (left_height + right_height + 1) );
return Math.max(left_height, right_height) + 1;
}
static int diameterOfTTree(Node root)
{
if(root == null)
return 0;
heightOfTree(root);
return diameter;
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
int arr[] = {10, 20, 30, 40, 60};
tree.root = tree.createTree(arr, 0);
int ans = diameterOfTTree(tree.root);
System.out.println("Answer is : " + ans);
}
}
Time complexity :- O(n)
Space complexity :- O(Height of the tree)
Comments
Post a Comment