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.
好吧這個題,就相當於統計深度了。
/**
* 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:
bool isBalanced(TreeNode* root)
{
if (root == NULL)
return true;
return isBalanced(root->left) && isBalanced(root->right) && abs(maxdepth(root->left) - maxdepth(root->right)) <= 1;
}
int maxdepth(TreeNode* root)
{
if (root == NULL)
return 0;
else
return (1 + max(maxdepth(root->left),maxdepth(root->right)));
}
int max(int a, int b)
{
if (a < b)
return b;
else
return a;
}
};