minimum height logic

This commit is contained in:
C9P8CS
2026-06-18 08:09:12 +05:30
parent b3cc80944a
commit 57a13a68f0
@@ -32,6 +32,7 @@ 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);
}
@@ -74,4 +75,13 @@ public class LevelOrderTraversal {
}
return res;
}
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;
}
}