Skip to content

Instantly share code, notes, and snippets.

@WennderSantos
Last active December 17, 2018 01:44
Show Gist options
  • Select an option

  • Save WennderSantos/e8b6872b4af9dba27407f41a60bba916 to your computer and use it in GitHub Desktop.

Select an option

Save WennderSantos/e8b6872b4af9dba27407f41a60bba916 to your computer and use it in GitHub Desktop.
Get the height of a binary tree. O(n)
class Node
{
public Node(int data) => Data = data;
public int Data { get; }
public Node Left { get; set; }
public Node Rigth { get; set; }
public void Add(int value)
{
if (value < Data)
{
if (Left is null)
Left = new Node(value);
else
Left.Add(value);
}
else
{
if (Rigth is null)
Rigth = new Node(value);
else
Rigth.Add(value);
}
}
public int Height() => Math.Max(Left is null ? -1 : Left.Height(),
Rigth is null ? -1 : Rigth.Height())
+ 1;
class Program
{
static void Main(string[] args)
{
var root = new Node(60);
root.Add(50);
root.Add(55);
root.Add(40);
root.Add(65);
root.Add(63);
root.Add(67);
Console.WriteLine(root.Height()); //2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment