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:进行DFS递归算出两边长度,然后进行比较,依次进行上述比较的递归 得到结果
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isBalanced(struct TreeNode* root) {
if (root==NULL)
return true;
int suml=depth(root->left);
int sumr=depth(root->right);
if(abs(suml-sumr)>1)
return false;
return (isBalanced(root->left)&&isBalanced(root->right));
}
int depth(struct TreeNode* nodes)
{
if (nodes==NULL)
return 0;
int suml=depth(nodes->left);
int sumr=depth(nodes->right);
return suml>sumr?suml+1:sumr+1;
}