using System.Collections.Generic;
public static void Main() {
int ? [] data = {1,2,2,3,3,null,null,4,4};
BinaryTree aBinaryTree = new BinaryTree(data);
bool status = IsBalanced(aBinaryTree);
Console.WriteLine(status);
static bool IsBalanced(BinaryTree root) {
int chk = CheckBalance(root.Root, 0);
static int CheckBalance(TreeNode root, int depth) {
int left = CheckBalance(root.left, depth + 1);
int right = CheckBalance(root.right, depth + 1);
if (Math.Abs(left - right) > 1)
return GetMax(left, right);
static int GetMax(int left, int right) {
public TreeNode(int ? val = 0, TreeNode left = null, TreeNode right = null) {
public BinaryTree(int ? [] data) {
if (data.Length == 0) return;
var queue = new Queue < TreeNode > ();
Root = new TreeNode(data[0]);
for (int i = 1; i < data.Length; i++) {
TreeNode presentNode = queue.Dequeue();
presentNode.left = new TreeNode(data[i]);
queue.Enqueue(presentNode.left);
if (i >= data.Length) break;
presentNode.right = new TreeNode(data[i]);
queue.Enqueue(presentNode.right);