题目
实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下,任意一个节点,其两颗子树的高度差不超过1。
分析
判断平衡二叉树是一个常见题目,一般来说,我们都是求出左右子树的高度,根据定义判断其差。下面给出三种实现方法,大家可以对比其优劣。
代码
/*
题目描述
实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,
其两颗子树的高度差不超过1。
给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。
*/
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Balance {
public:
/*方法一: T(n)=O(nlogn)*/
bool isBalance(TreeNode* root) {
// write code here
if (!root)
return true;
else if (abs(height(root->left) - height(root->right)) > 1)
return false;
else
return isBalance(root->left) && isBalance(root->right);
}
//求二叉树高度
int height(TreeNo