-->
当前位置:首页 > 题库 > 正文内容

程序填空题:Balanced Tree [1]

Luz4年前 (2021-05-10)题库629
A binary tree is said to be "height balanced" if both its left and right subtrees are height balanced, and the heights of its left and right subtrees can differ by at most 1. That is, $$|H_L - H_R |\le 1$$ where $$H_L$$ and $$H_R$$ are the heights of the left and right subtrees, respectively. An empty binary tree is defined to be height balanced.

The function `IsBalanced` is to judge if a given binary tree `T` is height balanced. If the answer is yes then return `true` and store the tree height in the parameter `pHeight`, else simply return `false`. The height of an empty tree is defined to be 0.

```c++
typedef struct TNode *BinTree;
struct TNode{
int Key;
BinTree Left;
BinTree Right;
};

bool IsBalanced ( BinTree T, int *pHeight )
{
int LHeight, RHeight, diff;

if( T == NULL) {
*pHeight = 0;
return true;
}
else if ( IsBalanced(T->Left, &LHeight) && IsBalanced(T->Right, &RHeight) ) {
diff = LHeight - RHeight;
if ( @@[diff<=1 && diff>= -1](3) ) {
*pHeight = 1 + ( diff>0 ? @@[LHeight : RHeight](3) );
return true;
}
else return false;
}
return false;
}
```





答案:
第1空:diff<=1 && diff>= -1

第2空:LHeight : RHeight

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。