平衡二叉树(java)
2018-06-21 本文已影响0人
夏臻Rock
题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
分析:
把这道题目放在二叉树的深度一题后面,真的是让人很开心啊,一下子就写好了,创解题速度之最。
解答:
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null) return true; //空树也认为是平衡的
//平衡树的左右子树高度差最大为1
return (Math.abs(getDepth(root.left)-getDepth(root.right))<=1)?true:false;
}
private static int getDepth(TreeNode node) {
return (node == null )? 0 : 1+Math.max(getDepth(node.left), getDepth(node.right));
}
}
