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)树主要就是根节点为空,叶子节点,一条边为空的情况需要讨论。
2)平衡树需要多讨论两个子节点的高度差是否大于1,以及子节点是否是平衡树。
/**
* Definition for binary tree* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int height(TreeNode *node)
{
if(NULL == node)
return 0;
if((NULL == node -> left) && (NULL == node -> right))
return 1;
if(NULL == node->left)
return 1+height(node->right);
if(NULL == node->right)
return 1+height(node->left);
if(height(node->left)>height(node->right))
return 1+height(node->left);
else
return 1+height(node->right);
}
bool isBalanced(TreeNode *root) {
if(NULL == root)
return true;
if((NULL == root->left) && (NULL == root->right))
return true;
int dist = height(root->left) - height(root->right);
if(dist > 1||dist < -1)
{
return false;
}
if(isBalanced(root->right)&&isBalanced(root->left))
return true;
else
return false;
}
};