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、他的右子树是平衡二叉树
3、他的左右子树的深度之差小于等于1
#include<iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int depthTree(TreeNode *root)
{
if(root == NULL)
return 0;
return max(depthTree(root->left) + 1,depthTree(root->right) + 1);
}
bool isBalanced(TreeNode *root) {
if(root == NULL)
return true;
if(isBalanced(root->left) && isBalanced(root->right) && abs( depthTree(root->left)-depthTree(root->right) )<=1 )
{
return true;
}else{
return false;
}
}
int main(void)
{
system("pause");
return 0;
}