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;
else{
return isBalanced(root->left) && isBalanced(root->right) && (maxDepth(root->left) - maxDepth(root->right) <= 1) && (maxDepth(root->left) - maxDepth(root->right) >= -1);
}
}
int maxDepth(TreeNode* root) {
if (root == NULL)
return 0;
else{
int left, right;
left = maxDepth(root->left) + 1;
right = maxDepth(root->right) + 1;
return left > right ? left : right;
}
}
};