tree diameter

This commit is contained in:
2026-06-18 08:33:27 +05:30
parent 57a13a68f0
commit c813a12cd9
@@ -76,6 +76,22 @@ public class LevelOrderTraversal {
return res;
}
private static int diameter = 0;
public static int diameterOfBinaryTree(TreeNode root) {
diameter = 0;
if (root == null) return 0;
heightOfBT(root);
return diameter - 1;
}
public static int heightOfBT(TreeNode root) {
if (root == null) return 0;
int leftHeight = heightOfBT(root.left);
int rightHeight = heightOfBT(root.right);
diameter = Math.max(leftHeight + rightHeight + 1, diameter);
return Math.max(leftHeight, rightHeight) + 1;
}
public static int minDepth(TreeNode root) {
if(root == null) return 0;
int leftHeight = minDepth(root.left);