Skip to content

Instantly share code, notes, and snippets.

@jj09
Created November 13, 2013 22:22
Show Gist options
  • Save jj09/7457573 to your computer and use it in GitHub Desktop.
Save jj09/7457573 to your computer and use it in GitHub Desktop.
Check whether tree is balanced.
using System;
public class Node
{
public Node Left {get;set;}
public Node Right {get;set;}
public object Value {get;set;}
}
public class Tree
{
public Node Root {get;set;}
public int? minHeight = null;
public int? maxHeight = null;
public bool IsBalanced()
{
maxHeight = null;
minHeight = null;
CalcHeight(Root, 0);
return maxHeight-minHeight < 2;
}
public void CalcHeight(Node node, int height)
{
if(node == null)
{
if(minHeight==null)
{
minHeight = height;
}
else
{
minHeight = height<minHeight ? height : minHeight;
}
if(maxHeight == null)
{
maxHeight = height;
}
else
{
maxHeight = height>maxHeight ? height : maxHeight;
}
}
else
{
CalcHeight(node.Left, height+1);
CalcHeight(node.Right, height+1);
}
}
}
public class Test
{
public static void Main()
{
Tree tree = new Tree();
Node root = new Node();
tree.Root = root;
tree.Root.Left = new Node();
tree.Root.Right = new Node();
tree.Root.Left.Left = new Node();
tree.Root.Left.Right = new Node();
tree.Root.Right.Left = new Node();
tree.Root.Right.Right = new Node();
if(tree.IsBalanced())
{
Console.WriteLine("Balanced");
}
else
{
Console.WriteLine("Not Balanced");
}
Console.WriteLine("Max: " + tree.maxHeight + " Min: " + tree.minHeight);
tree.Root.Right.Right.Right = new Node();
tree.Root.Right.Right.Right.Right = new Node();
if(tree.IsBalanced())
{
Console.WriteLine("Balanced");
}
else
{
Console.WriteLine("Not Balanced");
}
Console.WriteLine("Max: " + tree.maxHeight + " Min: " + tree.minHeight);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment