Created
November 13, 2013 22:22
-
-
Save jj09/7457573 to your computer and use it in GitHub Desktop.
Check whether tree is balanced.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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