判断二叉树树是否是平衡二叉树
程序员文章站
2022-05-16 11:24:19
...
package com.tree;
public class IsBalanceTree {
public static boolean isBalanceTree(TreeNode root,int[] dep){
if(root==null){
dep[0] = 0;
return true;
}
int[] leftDep = new int[1];
int[] rightDep = new int[1];
if(isBalanceTree(root.left,leftDep)&&isBalanceTree(root.right,rightDep)){
int diff = leftDep[0]-rightDep[0];
if(diff>=-1&&diff<=1){
dep[0] = 1 + (leftDep[0] > rightDep[0] ? leftDep[0] : rightDep[0]);
return true;
}
}
return false;
}
private class TreeNode {
private TreeNode left;
private TreeNode right;
private Integer val;
public TreeNode(Integer val) {
this.val = val;
}
}
}
上一篇: 全网最强红黑树的理解和实现
下一篇: 加载网络图片