Amazon Interview Question
Software Engineer in TestsCountry: United States
Interview Type: Phone Interview
Balanced tree is
(1)an empty tree
(2)left subtree is a balanced tree && right subtree is a balanced tree &&
abs(height difference of the two subtrees) <= 1
Following is C++ codeļ¼
bool isBalanced(Node* root) //interface to outside
{
int height;
return isBalanced(root, height);
}
bool isBalanced(Node* p, int& height)
{
if(p == NULL){
height = 0;
return true;
}
int leftHeight, rightHeight;
if(isBalanced(p->left, leftHeight) &&
isBalanced(p->right, rightHeight) &&
abs(leftHeight - rightHeight) <= 1
){
height = 1 + max(leftHeight, rightHeight);
return true;
}
return false;
}
int isBalanced(Node *root){
int hl,hr;
if(root == NULL)
return 1;
hl = height(root->left);
hr = height(root->right);
if(abs(hl-hr) <=1 && isBalanced(root>left) && isBalanced(root->right))
return 1;
return 0;
}
int height(Node* root){
if(root == NULL){
return 0;
}
return 1 + max(height(root->left),height(root->right));
}
A balanced tree is one in which
height of left subtree - height of right subtree is atmost 1.
A naive approch would be:
1. start from root
2. while an unvisited node exists, check if the subtree rooted at that node is balanced or not
3. if all such subtrees are balanced then return true else return false
int isBalanced(Node *root)
{
if(root==NULL)
return 1;
int lHeight = height(root->left);
int rheight = height(root->right);
if(abs(lHeight-rHeight) > 1)
return 0;
return isBalanced(root->left)&&isBalanced(root->right);
}
int height(Node* root){
if(root == NULL)
{
return 0;
}
return 1 + max(height(root->left),height(root->right));
}
This approach checks the height for every node. So time complexity is O(nlgn)
To reduce the time complexity we can modify the height function. We can use a flag which will be set at the level the heights mismatch. So while calculating the height of the tree it will also check if the tree is balanced or not.
int height(Node* root, int* balanced) //initially balanced = 0
{
if(root==NULL)
return 0;
int lHeight = height(root->left,balanced);
int rHeight = height(root->right,balanced);
if(abs(lHeight-rHeight)>1)
*balanced = 1; //setting the flag
return max(lHeight,rHeight)+1
}
if balanced = 1 => Tree is not height balanced
This will reduce the time complexity to O(n)
Complexity : O(n)
- srdjan December 25, 2013