題目連結:https://leetcode.com/problems/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.
思路:求解一個樹是否平衡可以轉化為求二叉樹的深度,一旦發現左右子樹深度相差超過1,則說明不是平衡樹。
代碼如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int height(TreeNode* root)
{
if(!root) return 0;
int left = height(root->left);
if(left==-1) return -1;
int right = height(root->right);
if(right==-1) return -1;
if(abs(left-right)>1) return -1;
return max(left, right)+1;
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
return height(root)==-1?false:true;
}
};