1.题目描述
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.
2.解法分析
判断一个树是否为平衡二叉树与求树的深度如出一辙,只是返回值有两个,一个是当前树是否为平衡二叉树,另一个是当前树的高度。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!root)return true;int depth;
return myJudge(root,depth);
}bool myJudge(TreeNode *root,int &depth){if(root==NULL)
{depth=0;return true;
}int depth_left;
int depth_right;
bool lj=myJudge(root->left,depth_left);
if(!lj)return false;bool rj=myJudge(root->right,depth_right);
if(!rj)return false;depth = max(depth_left,depth_right)+1;if((depth-1-min(depth_left,depth_right))<=1)return true;else return false;}};