tree functions segregation

This commit is contained in:
2026-06-18 11:06:16 +05:30
parent c813a12cd9
commit 3ca995f7ad
2 changed files with 61 additions and 26 deletions
@@ -32,7 +32,6 @@ public class LevelOrderTraversal {
for (List<Integer> level : list) {
System.out.println(level);
}
System.out.println("MinDepth: " + minDepth(root));
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -75,29 +74,4 @@ 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);
int rightHeight = minDepth(root.right);
if (leftHeight == 0) return rightHeight + 1;
if (rightHeight == 0) return leftHeight + 1;
return Math.min(leftHeight, rightHeight) + 1;
}
}