判断一棵树是否是平衡二叉树
程序员文章站
2022-05-16 14:56:10
...
//判断一棵树是否是平衡二叉树
public class Main18 {
public static void main(String[] args) {
TreeNode tree = new TreeNode(1);
tree.left = new TreeNode(2);
tree.right = new TreeNode(3);
tree.left.left = new TreeNode(4);
tree.left.right = new TreeNode(5);
// int deep = treeDeep(tree);
System.out.println(isBalancedTree(tree));
}
//获取树的深度,采用递归的方式
public static int treeDeep(TreeNode treeNode){
if(treeNode == null) return 0;
//左子树深度
int leftDeep = treeDeep(treeNode.left);
//右子树深度
int rightDeep = treeDeep(treeNode.right);
return Math.max(leftDeep+1,rightDeep+1);
}
//判断是否是平衡二叉树,即判断每个节点下的左子树与右子树的高度差的绝对值
public static boolean isBalancedTree(TreeNode treeNode){
if(treeNode == null) return true;
//获得左子树的高度
int leftChild = treeDeep(treeNode.left);
int rightChild = treeDeep(treeNode.right);
//高度差
int dep = Math.abs(leftChild-rightChild);
if(dep>1) return false;
return isBalancedTree(treeNode.left)&&isBalancedTree(treeNode.right);
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val){
this.val = val;
}
}
上一篇: 判断一棵二叉树是否是平衡二叉树