首页 > 代码库 > LeetCode OJ - Balanced Binary Tree
LeetCode OJ - Balanced Binary Tree
判断树是否是平衡的,这道题中的平衡的概念是指任意节点的两个子树的高度相差不超过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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。