题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
***************************************************************************************************************************************************
知识点复习(求二叉树的深度)
求二叉树的深度,先求左子树的深度,再求右子树的深度,然后返回两者之间的最大值加 1 ,就是整棵树的深度。
这正对应于先序遍历左子树(得到左子树的深度 left),再遍历右子树(得到右子树的深度 right ),最后访问根(得到整棵树的深度 max{left, right} + 1)的后序遍历方式。
***************************************************************************************************************************************************
平衡二叉树的定义:
它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是平衡二叉树。
思路
遍历每个节点,借助一个获取树深度的递归函数,根据该节点的左右子树高度差判断是否平衡;
然后递归地对左右子树判断。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
else{
return Math.abs(getDepth(root.left) - getDepth(root.right))<= 1 &&
IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
}
public static int getDepth(TreeNode root){
if(root == null)
return 0;
else{
int left = getDepth(root.left);//左
int right = getDepth(root.right);//右
return Math.max(left, right) + 1;//根,(左、右、根,对应的是后序遍历)
}
}
}
参考思路2
思路1有很明显的问题,在判断上层结点的时候,会多次重复遍历下层结点,增加了不必要的开销。如果改为从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。
public class Solution {
boolean flag = true;
public boolean IsBalanced_Solution(TreeNode root) {
int depth = getDepth(root);
return flag;
}
public int getDepth(TreeNode root){
if(root == null)
return 0;
else{
int left = getDepth(root.left);
int right = getDepth(root.right);
if((Math.abs(left -right)) > 1)
flag = false;
return Math.max(left, right) + 1;
}
}
}
转载:https://blog.csdn.net/qq_28632639/article/details/102231030