File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
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
+ }
You can’t perform that action at this time.
0 commit comments