Interview Question
Team: SQL Server / DPG Group
Country: United States
Interview Type: In-Person
private static boolean isBalanced(TreeNode01 root) {
return ((maxDepth(root) - minDepth(root)) <= 1);
}
private static int maxDepth(TreeNode01 root) {
if (root == null) {
return -1;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
private static int minDepth(TreeNode01 root) {
if(root.right == null && root.left == null) {
return 0;
}
if(root.left == null && root.right != null) {
return 1 + minDepth(root.right);
}
if(root.right == null && root.left != null) {
return 1 + minDepth(root.left);
}
else {
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}
if modular difference of depth(left) and depth(right) is greater than 1 then tree is not balanced.
- Pavan October 15, 2012