Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路一:
当一个二叉树的左子树和右子树都是平衡二叉树,且左右子树深度之差小于等于1,即可判断该二叉树为平衡二叉树。
1 public boolean isBalanced(TreeNode root) { 2 if(root == null) { 3 return true; 4 } 5 boolean cut = false; 6 if(root.right == null || root.left == null) { 7 cut = true; 8 } 9 return isBalanced(root.left) && isBalanced(root.right) 10 && Math.abs(getDepth(root.left, cut) - getDepth(root.right, cut)) <= 1; 11 } 12 public int getDepth(TreeNode root, boolean cut) { 13 if(root == null) { 14 return 0; 15 } 16 if(cut && (root.left != null || root.right != null)) { 17 //当前子树至少是2,另一颗子树是0的情况,直接返回 18 return 2; 19 } 20 return Math.max(getDepth(root.left, false), getDepth(root.right, false)) + 1; 21 }