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. // Balanced Binary Tree
  2. // 时间复杂度O(n),空间复杂度O(logn)
  3. public class Solution {
  4. public boolean isBalanced (TreeNode root) {
  5. return balancedHeight (root) >= 0;
  6. }
  7. /**
  8. * Returns the height of `root` if `root` is a balanced tree,
  9. * otherwise, returns `-1`.
  10. */
  11. private static int balancedHeight (TreeNode root) {
  12. if (root == null) return 0; // 终止条件
  13. int left = balancedHeight (root.left);
  14. int right = balancedHeight (root.right);
  15. if (left < 0 || right < 0 || Math.abs(left - right) > 1) return -1; // 剪枝
  16. return Math.max(left, right) + 1; // 三方合并
  17. }
  18. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/binary-tree/traversal/balanced-binary-tree.html