程序填空题:Balanced Tree [3]
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 + 1;
if ( @@[diff<=2 && diff>= 0](3) ) {
*pHeight = 1 + ( diff<1 ? @@[RHeight : LHeight](3) );
return true;
}
else return false;
}
return false;
}
```
答案:
第1空:diff<=2 && diff>= 0
第2空:RHeight : LHeight
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 + 1;
if ( @@[diff<=2 && diff>= 0](3) ) {
*pHeight = 1 + ( diff<1 ? @@[RHeight : LHeight](3) );
return true;
}
else return false;
}
return false;
}
```
答案:
第1空:diff<=2 && diff>= 0
第2空:RHeight : LHeight