输入一棵二叉树,判断该二叉树是否是平衡二叉树。
定义:平衡二叉查找树,简称平衡二叉树。
遍历每个结点,借助一个获取树深度的递归函数,根据该结点的左右子树高度差判断是否平衡,然后递归地对左右子树进行判断。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
return Math.abs(maxDept(root.left) - maxDept(root.right)) <=1 &&
IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
public int maxDept(TreeNode root){
if(root == null)
return 0;
return 1 + Math.max(maxDept(root.left), maxDept(root.right));
}
}
版权属于: 尾尾部落
原文地址: https://weiweiblog.cn/isbalanced_solution/
转载时必须以链接形式注明原始出处及本声明。
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"1","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')0||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];