題目:
Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路:
判斷二叉平衡樹。
寫一個BalancedHeight 函數用來計算某一節點的高度,然後對當前節點求其左右子樹的高度差,最後遞歸檢查其左右子樹是否平衡。
C++ AC代碼:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
if ( root == NULL )
return true;
if ( abs(BalancedHeight(root->left) - BalancedHeight(root->right)) > 1)
return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int BalancedHeight (TreeNode* root){
if ( root == NULL ) return 0;
int left = BalancedHeight (root->left);
int right = BalancedHeight (root->right);
return 1+max(left,right);
}
};