|
| 1 | +// Source : https://oj.leetcode.com/problems/balanced-binary-tree/ |
| 2 | +// Inspired by : http://www.jiuzhang.com/solutions/balanced-binary-tree/ |
| 3 | +// Author : Lei Cao |
| 4 | +// Date : 2015-10-07 |
| 5 | + |
| 6 | +/********************************************************************************** |
| 7 | + * |
| 8 | + * Given a binary tree, determine if it is height-balanced. |
| 9 | + * |
| 10 | + * For this problem, a height-balanced binary tree is defined as a binary tree in which |
| 11 | + * the depth of the two subtrees of every node never differ by more than 1. |
| 12 | + * Example |
| 13 | + * Given binary tree A={3,9,20,#,#,15,7}, B={3,#,20,15,7} |
| 14 | + * The binary tree A is a height-balanced binary tree, but B is not. |
| 15 | + **********************************************************************************/ |
| 16 | + |
| 17 | +package balancedBinaryTree; |
| 18 | + |
| 19 | +/** |
| 20 | + * Created by leicao on 7/10/15. |
| 21 | + */ |
| 22 | +public class balancedBinaryTree { |
| 23 | + /** |
| 24 | + * @param root: The root of binary tree. |
| 25 | + * @return: True if this Binary tree is Balanced, or false. |
| 26 | + */ |
| 27 | + public boolean isBalanced(TreeNode root) { |
| 28 | + // write your code here |
| 29 | + return helper(root, 0).isBalanced; |
| 30 | + } |
| 31 | + |
| 32 | + // This is not needed. Can just check the depth |
| 33 | + private class Result { |
| 34 | + boolean isBalanced; |
| 35 | + int height; |
| 36 | + Result(boolean isBalanced, int height) { |
| 37 | + this.isBalanced = isBalanced; |
| 38 | + this.height = height; |
| 39 | + } |
| 40 | + } |
| 41 | + private Result helper(TreeNode root, int depth) { |
| 42 | + if (root == null) { |
| 43 | + return new Result(true, depth); |
| 44 | + } |
| 45 | + Result left = helper(root.left, depth + 1); |
| 46 | + Result right = helper(root.right, depth + 1); |
| 47 | + |
| 48 | + if (!left.isBalanced || !right.isBalanced) { |
| 49 | + return new Result(false, 0); |
| 50 | + } |
| 51 | + |
| 52 | + if (Math.abs(left.height - right.height) > 1) { |
| 53 | + return new Result(false, 0); |
| 54 | + } |
| 55 | + return new Result(true, Math.max(left.height, right.height)); |
| 56 | + } |
| 57 | +} |
0 commit comments