判断树是否是平衡的,这道题中的平衡的概念是指任意节点的两个子树的高度相差不超过1,我用递归的方法把所有的节点的高度都计算了下,并且在计算的过程记录每个节点左右两颗子树的高度差,最后通过遍历这个高度差就可以知道是否是平衡的。
下面是AC代码:
1 /** 2 * Given a binary tree, determine if it is height-balanced. 3 * For this problem, a height-balanced binary tree is defined as a binary tree 4 * in which the depth of the two subtrees of every node never differ by more than 1. 5 * @param root 6 * @return 7 */ 8 public boolean isBalanced(TreeNode root){ 9 ArrayList<Integer> hd = new ArrayList<Integer>(); 10 heightRec(root, hd); 11 for(int i: hd) 12 if(i>1) 13 return false; 14 return true; 15 } 16 /** 17 * 18 * @param root 19 * @param difference is for recording the difference of the height between the two subtrees 20 * @return 21 */ 22 private int heightRec(TreeNode root, ArrayList<Integer> difference){ 23 if(root == null) 24 return 0; 25 if(root.left==null && root.right ==null) 26 return 1; 27 int leftH = heightRec(root.left, difference); 28 int rightH = heightRec(root.right,difference); 29 difference.add(Math.abs(leftH-rightH)); 30 return Math.max(leftH, rightH )+1; 31 }