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;
}
}
};