此题出自牛客网的剑指offer专题
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解题思路
平衡二叉树的定义:平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
思路一:获取左子树与右子树的高度,并判断两棵子树的高度差是否大于1,若大于则说明该树不是平衡二叉树,直接返回false,若小于等于,则继续遍历该树直至该树遍历完毕,此时则说明该树是一棵平衡二叉树。返回true
思路二:思路一有很明显的问题,在判断上层结点的时候,会多次重复遍历下层结点,增加了不必要的开销。如果改为从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次
实现代码
Java版本
思路一实现代码
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){
return true;
}
if(Math.abs(getHeight(root.left)-getHeight(root.right))>1){
return false;
}
return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
}
public int getHeight(TreeNode root){
if(root==null){
return 0;
}
int left = getHeight(root.left);
int right = getHeight(root.right);
return left>right? left+1:right+1;
}
}
思路二实现代码
public class Solution {
Boolean isBalanced = true;
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){
return isBalanced;
}
getDepth(root);
return isBalanced;
}
public int getDepth(TreeNode root){
if(root==null){
return 0;
}
int left = getDepth(root.left);
int right = getDepth(root.right);
if(Math.abs(left-right)>1){
isBalanced = false;
}
return left>right? left+1:right+1;
}
}
C++版本
思路一实现代码:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL)
{
return true;
}
int flag = getHeight(pRoot->left) - getHeight(pRoot->right);
if(flag>1 || flag<-1)
{
return false;
}
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
//获取树的高度
int getHeight(TreeNode* pRoot){
if(pRoot == NULL)
{
return 0;
}
int left = getHeight(pRoot->left);
int right = getHeight(pRoot->right);
return left>right? left+1:right+1;
}
};
思路二实现代码
class Solution {
bool isBalanced = true;
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL)
{
return isBalanced;
}
getDepth(pRoot);
return isBalanced;
}
int getDepth(TreeNode* pRoot)
{
if(pRoot == NULL)
{
return 0;
}
int left = getDepth(pRoot->left);
int right = getDepth(pRoot->right);
int flag = left-right;
if(flag>1 || flag<-1)
{
isBalanced = false;
}
return left>right? left+1:right+1;
}
};