Balanced Binary Tree
Total
Accepted: 85721 Total
Submissions: 261445 Difficulty: Easy
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).判斷root是否平衡(即左右子樹的高是否相差在1 內),平衡轉2).,如果不平衡,則返回false;
2).判斷root的左子樹是否平衡,root的右子樹是否平衡,即把root的左右節點當成root並重復1).
3).直到NULL結束。
/**
* 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 getHeight(TreeNode* root){
if(root==NULL){
return 0;
}else{
return max(getHeight(root->left),getHeight(root->right))+1;
}
}
bool isBalanced(TreeNode* root) {
if(root==NULL){
return true;
}
int m = getHeight(root->left);
int n = getHeight(root->right);
if(abs(n-m)<=1){
return isBalanced(root->left)&&isBalanced(root->right);
}else{
return false;
}
}
};