Skip to content

Commit 6515c41

Browse files
author
applewjg
committed
BalancedBinaryTree
Change-Id: If9f723c145b20b9a8ef6e66cf0e14d88c96ffaa5
1 parent 324948c commit 6515c41

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

BalancedBinaryTree.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Oct 07, 2014
4+
Problem: Balanced Binary Tree
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/balanced-binary-tree/
7+
Notes:
8+
Given a binary tree, determine if it is height-balanced.
9+
For this problem, a height-balanced binary tree is defined as a binary tree in which
10+
the depth of the two subtrees of every node never differ by more than 1.
11+
12+
Solution: DFS.
13+
*/
14+
/**
15+
* Definition for binary tree
16+
* public class TreeNode {
17+
* int val;
18+
* TreeNode left;
19+
* TreeNode right;
20+
* TreeNode(int x) { val = x; }
21+
* }
22+
*/
23+
public class Solution {
24+
public boolean isBalanced(TreeNode root) {
25+
if (root == null) return true;
26+
return isBalancedRe(root) > -1;
27+
}
28+
public int isBalancedRe(TreeNode root) {
29+
if (root == null) return 0;
30+
int left = isBalancedRe(root.left);
31+
int right = isBalancedRe(root.right);
32+
if (left == -1 || right == -1) return -1;
33+
if (Math.abs(left - right) > 1) return -1;
34+
return Math.max(left, right) + 1;
35+
}
36+
}

0 commit comments

Comments
 (0)