-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1382BalanceABinarySearchTree.cs
More file actions
58 lines (51 loc) · 1.68 KB
/
1382BalanceABinarySearchTree.cs
File metadata and controls
58 lines (51 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Collections.Generic;
using System.Text;
namespace CodeForecs
{
class _1382BalanceABinarySearchTree
{
/**
* Definition for a binary tree node.
* */
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution
{
public int GetHeight(TreeNode root)
{
if (root == null)
return 0;
int leftHeight = GetHeight(root.left);
int rightHeight = GetHeight(root.right);
return 1 + Math.Max(leftHeight, rightHeight);
}
public TreeNode BalanceBST(TreeNode root)
{
int leftHeight = GetHeight(root.left);
int rightHeight = GetHeight(root.right);
Console.Write("Left Height :- ");
Console.WriteLine(leftHeight);
Console.Write("Right Height :- ");
Console.WriteLine(rightHeight);
if(leftHeight - rightHeight >= 2)
{
TreeNode temp = root;
root = root.left;
root.right = temp;
}
else if (rightHeight - leftHeight >= 2)
{
TreeNode temp = root;
root = root.right;
root.left = temp;
}
return root;
}
}
}
}