Skip to content

Instantly share code, notes, and snippets.

@BeautyfullCastle
Created August 26, 2020 16:23
Show Gist options
  • Save BeautyfullCastle/9dbb52ed2bf8408a080e254bd534248b to your computer and use it in GitHub Desktop.
Save BeautyfullCastle/9dbb52ed2bf8408a080e254bd534248b to your computer and use it in GitHub Desktop.
Array to Binary Search Tree
using System;
using System.Text;
namespace PracticeAlgorithmCSharp
{
public class Tree
{
private readonly Node root;
public Tree(int[] arr)
{
root = CreateRecurive(arr, 0, arr.Length - 1);
}
private Node CreateRecurive(int[] arr, int startIdx, int endIdx)
{
if (startIdx > endIdx)
{
return null;
}
int midIdx = (startIdx + endIdx) / 2;
Node node = new Node()
{
Value = arr[midIdx],
LeftChild = CreateRecurive(arr, startIdx, midIdx - 1),
RightChild = CreateRecurive(arr, midIdx + 1, endIdx)
};
return node;
}
public void Print()
{
StringBuilder sb = new StringBuilder();
PrintRecursive(root, sb);
Console.WriteLine(sb);
}
private void PrintRecursive(Node node, StringBuilder sb)
{
if (node == null)
{
return;
}
PrintRecursive(node.LeftChild, sb);
sb.Append(node.Value).Append(" ");
PrintRecursive(node.RightChild, sb);
}
private class Node
{
public int Value { get; set; }
public Node LeftChild { get; set; }
public Node RightChild { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment