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.
题目给出了平衡二叉树的定义即每个节点的两个子树的高不能相差大于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:
int getHeight(TreeNode* root)
{
int height = 0,lheight = 0,rheight = 0;
if(root != NULL) ++height;
if(root->left != NULL) lheight = getHeight(root->left);
if(root->right != NULL) rheight = getHeight(root->right);
return lheight>rheight?(height+lheight):(height+rheight);
}
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
int lheight = 0,rheight = 0;
if(root->left != NULL){
lheight = getHeight(root->left);
}
if(root->right != NULL){
rheight = getHeight(root->right);
}
cout<<lheight<<endl;
cout<<rheight<<endl;
if(lheight-rheight <=1&& lheight-rheight>=-1)
{
return isBalanced(root->left)&&isBalanced(root->right);
}
else
return false;
}
};