平衡二叉树,题目如链接。
这个题可以用前面的二叉树的深度来解决,也就是写两个函数,一个用来计算二叉树的深度,另一个判断是否是平衡二叉树;然后递归到左右子树。
class Solution {
public:
/*
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode * root) {
// write your code here
return depth(root)!=-1;
} //判断
int depth(TreeNode *root)
{
if(root==NULL)return 0;
int left=depth(root->left);
int right=depth(root->right);
if(left==-1||right==-1||abs(left-right)>1)return -1;
return max(left,right)+1;
}//深度算法
};