注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
本帖最后由 brilight 于 2013-2-25 22:43 编辑
career 4.1
題目:Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one .
對於上面的tree,root左邊是 height=2的subtree,是balanced的;root右邊是 height =3的subtree,是balanced;所以整個tree是balanced。
或者可參考 http://www.cs.auckland.ac.nz/~jmor159/PLDS210/AVL.html, 裡面有類似的例子
我們再看 careercup書上的答案 對於上面的 tree, 返回的是not balanced。
代碼如下:
int min_depth( Node * root ) {
if( !root ) return 0;
return 1 + min( min_depth( root->left ),
min_depth( root->right ));
}
int max_depth( Node * root ) {
if( !root ) return 0;
return 1 + max( max_depth( root->left ),
max_depth( root->right ));
}
bool is_balanced( Node * root ) {
return ( max_depth( root ) - min_depth( root ) ) <= 1
}
上面的代碼之所以不對,是因為 min_depth=1, max_depth =3 , 返回的 not balanced.
判讀 tree是否balanced,應該看 左邊 max_depth 和 右邊 max_depth 的差,而不是min_depth 和 max_depth 的差。
我們再看 careercup 書上對於balanced的定義:a balanced tree is a tree which has no two leaf nodes differ in distance from the root by more than one .
我們可以找到一個反例,說明這個定義是錯誤的:如下圖,有2個leafs,高度差為0,但整個 tree 是unbalanced,原因是第二行的節點左右的subtree的高度不同。
我認為以下的代碼應該才是正確的解法
int treeHeightBalanced(NODE* p)
{
int leftHeight;
int rightHeight;
if(p==NULL) return 0;// balanced
leftHeight = treeHeightBalanced(p->left) ;
rightHeight = treeHeightBalanced(p->right) ;
if(leftHeight==-1 || rightHeight==-1)
return -1; //unbalanced
if(leftHeight- rightHeight >1 || leftHeight- rightHeight <-1)
return -1; // unbalanced
return 1+max(leftHeight,rightHeight); // balanced
}
|