File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * public int val;
5
+ * public TreeNode left;
6
+ * public TreeNode right;
7
+ * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
8
+ * this.val = val;
9
+ * this.left = left;
10
+ * this.right = right;
11
+ * }
12
+ * }
13
+ */
14
+ public class Solution
15
+ {
16
+
17
+ //T: O(N) and S: O(H)
18
+ public bool IsBalanced ( TreeNode root )
19
+ {
20
+ return checkHeight ( root ) != int . MinValue ;
21
+ }
22
+
23
+ private int checkHeight ( TreeNode root )
24
+ {
25
+ if ( root == null )
26
+ return - 1 ;
27
+ var leftHeight = checkHeight ( root . left ) ;
28
+ if ( leftHeight == int . MinValue ) return leftHeight ;
29
+
30
+ var rightHeight = checkHeight ( root . right ) ;
31
+ if ( rightHeight == int . MinValue ) return rightHeight ;
32
+
33
+ var heightDiff = leftHeight - rightHeight ;
34
+ if ( Math . Abs ( heightDiff ) > 1 )
35
+ return int . MinValue ;
36
+ else
37
+ return Math . Max ( leftHeight , rightHeight ) + 1 ;
38
+
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments