Skip to content

Commit 795c444

Browse files
Create 110-Balanced-Binary-Tree.cs
File(s) Modified: 1110-Balanced-Binary-Tree.cs Language(s) Used: csharp Submission URL: https://leetcode.com/submissions/detail/755514207/
1 parent b1ee6db commit 795c444

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: csharp/110-Balanced-Binary-Tree.cs

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

0 commit comments

Comments
 (0)