题目:
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.
分析:
分别计算出root左右子树的深度即可。但是我这个代码其实并没有写好。因为中间有很多量都重复了。有时间会改的。
代码:
/**
* 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;
int left=Depth(root->left);
int right=Depth(root->right);
return (left==right||left==right+1||left+1==right)&&isBalanced(root->left)&&isBalanced(root->right);
}
int Depth(TreeNode* root){
if(root==NULL)return 0;
int left=Depth(root->left)+1;
int right=Depth(root->right)+1;
return left>right?left:right;
}
};