## IBM Interview Question for Accountants

Country: United States

Comment hidden because of low score. Click to expand.
1
of 1 vote

Here is a neat code to check whether a tree is balanced or not,

puddleofriddles.blogspot.com/search?q=balanced

Comment hidden because of low score. Click to expand.
0

Order is O(n^2)

Comment hidden because of low score. Click to expand.
0

that's not order of n^2... that's 2n. So still O(n)

Comment hidden because of low score. Click to expand.
0
of 0 vote

int maxDepth(node* root)
{
if(NULL == root)
return 0;

int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);

return 1 + (leftDepth > rightDepth ? leftDepth:rightDepth);
}

int minDepth(node* root)
{
if(NULL == root)
return 0;

int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);

return 1 + (leftDepth < rightDepth ? leftDepth:rightDepth);
}

int isBalanced(node* root)
{
if(maxDepth(root) - minDepth(root) > 1)
return 0;
else
return 1;
}

Comment hidden because of low score. Click to expand.
0

Will this still be a correct solution.

public static int maxDepth(TreeNode root){
if(root == null){
return 0;
}
return 1+ Math.max(maxDepth(root.left), maxDepth(root.right));
}
public static boolean isBalanced(TreeNode root){
return (maxDepth(root.left) - minDepth(root.right) <= 1);

}

Why do we find MinDepth. Please explain.

Comment hidden because of low score. Click to expand.
0

i dont think it will be a correct solution... we have to find mindepth as well in order to check for each subtrees.. ur code without mindepth will onli check for main tree..

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````int checkBalance(Node n, Boolean flag) {

if(n == null) return -1;

int leftHeight = checkBalance(n.left) + 1;
int rightHeight = checkBalance(n.right) + 1;

if(Math.Abs(leftHeight - rightHeight) > 1) flag = true;

return max(leftHeight, rightHeight);

}

bool isBalance(Node n) {

Boolean flag = false;
checkBalance(n);
return flag;

}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.