Skip to content

Commit

Permalink
Create 110-Balanced-Binary-Tree.cs
Browse files Browse the repository at this point in the history
File(s) Modified: 1110-Balanced-Binary-Tree.cs
Language(s) Used: csharp
Submission URL: https://leetcode.com/submissions/detail/755514207/
  • Loading branch information
ShrujanKotturi committed Sep 29, 2022
1 parent b1ee6db commit 795c444
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions csharp/110-Balanced-Binary-Tree.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution
{

//T: O(N) and S: O(H)
public bool IsBalanced(TreeNode root)
{
return checkHeight(root) != int.MinValue;
}

private int checkHeight(TreeNode root)
{
if (root == null)
return -1;
var leftHeight = checkHeight(root.left);
if (leftHeight == int.MinValue) return leftHeight;

var rightHeight = checkHeight(root.right);
if (rightHeight == int.MinValue) return rightHeight;

var heightDiff = leftHeight - rightHeight;
if (Math.Abs(heightDiff) > 1)
return int.MinValue;
else
return Math.Max(leftHeight, rightHeight) + 1;

}
}

0 comments on commit 795c444

Please sign in to comment.