Skip to content

Instantly share code, notes, and snippets.

@aaronjwood
Created February 15, 2016 05:57
Show Gist options
  • Save aaronjwood/7e0fc962c5cd898b3181 to your computer and use it in GitHub Desktop.
Save aaronjwood/7e0fc962c5cd898b3181 to your computer and use it in GitHub Desktop.
Binary search tree implementation in C#
using System;
using System.Diagnostics;
namespace BinarySearchTree
{
class Node
{
public int value;
public Node left;
public Node right;
}
class Tree
{
public Node insert(Node root, int v)
{
if (root == null)
{
root = new Node();
root.value = v;
}
else if (v < root.value)
{
root.left = insert(root.left, v);
}
else
{
root.right = insert(root.right, v);
}
return root;
}
public void traverse(Node root)
{
if (root == null)
{
return;
}
traverse(root.left);
traverse(root.right);
}
}
class BinarySearchTree
{
static void Main(string[] args)
{
Node root = null;
Tree bst = new Tree();
int SIZE = 2000000;
int[] a = new int[SIZE];
Console.WriteLine("Generating random array with {0} values...", SIZE);
Random random = new Random();
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < SIZE; i++)
{
a[i] = random.Next(10000);
}
watch.Stop();
Console.WriteLine("Done. Took {0} seconds", (double)watch.ElapsedMilliseconds / 1000.0);
Console.WriteLine();
Console.WriteLine("Filling the tree with {0} nodes...", SIZE);
watch = Stopwatch.StartNew();
for (int i = 0; i < SIZE; i++)
{
root = bst.insert(root, a[i]);
}
watch.Stop();
Console.WriteLine("Done. Took {0} seconds", (double)watch.ElapsedMilliseconds / 1000.0);
Console.WriteLine();
Console.WriteLine("Traversing all {0} nodes in tree...", SIZE);
watch = Stopwatch.StartNew();
bst.traverse(root);
watch.Stop();
Console.WriteLine("Done. Took {0} seconds", (double)watch.ElapsedMilliseconds / 1000.0);
Console.WriteLine();
Console.ReadKey();
}
}
}
@junsp
Copy link

junsp commented Apr 5, 2020

One question is, what happens when the random generator returns many same values?

then they keep getting added to the right most node where it is null ?
wonder what these same values mean in BST.

@yermolenko-d
Copy link

Looks like there is a mistake
what will happens if root value equals v?

@aaronjwood
Copy link
Author

Thanks all, didn't realize this had so many comments until now!

To the question above: this implementation is allowing for duplicate values so line 26 will be taken. If you have a LOT of duplicate values this code will surely stack overflow. For example, change a[i] = random.Next(10000); to a[i] = random.Next(10);. If you change it to a[i] = random.Next(1000); the part that fills the tree takes an extremely long time to complete since you can imagine how inefficient it has become. Not good :)

@hyunbin7303
Copy link

Thanks a lot! It's really helpful.

@Farhadtavakoli
Copy link

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment