Balanced Binary Tre
e
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;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int depth(struct TreeNode *root) {
if (root == NULL)
return 0;
int left = depth(root->left);
int right = depth(root->right);
return (left > right ? left : right) + 1;
}
bool isBalanced(struct TreeNode* root) {
if (root == NULL)
return true;
int left = depth(root->left);
int right = depth(root->right);
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
原题地址:
https://leetcode.com/problems/balanced-binary-tree/