Skip to content

Instantly share code, notes, and snippets.

@tuliopaim
Last active March 23, 2021 15:52
Show Gist options
  • Select an option

  • Save tuliopaim/f564156ccc42de2b770110d9cc981851 to your computer and use it in GitHub Desktop.

Select an option

Save tuliopaim/f564156ccc42de2b770110d9cc981851 to your computer and use it in GitHub Desktop.
Simple Char Tree in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace TestingConsole
{
public class Node
{
private int Level { get; set; }
private List<Node> Children { get; set; }
public char Value { get; private set; }
public Node()
{
Level = 0;
Children = new List<Node>();
}
public Node(char value, int level)
{
Value = value;
Level = level;
Children = new List<Node>();
}
public static Node CreateTreeWithAllLetters()
{
var tree = new Node();
for (int i = 'a'; i <= 'z'; i++)
{
tree.Insert(((char)i).ToString());
}
return tree;
}
public void Insert(string value)
{
InsertNode(value, 0);
}
private void InsertNode(string value, int index)
{
if (index >= value.Length) return;
var letter = value[index];
var correctChild = Children.Find(c => c.Value.Equals(letter));
if (correctChild == null)
{
correctChild = new Node(letter, index + 1);
Children.Add(correctChild);
}
correctChild.InsertNode(value, index + 1);
}
public string PrintHorizontally()
{
return PrintHorizontally(this, 0, 0);
}
private string PrintHorizontally(Node node, int level, int distanceFromStart)
{
var finalStr = "";
if (node.Level != 0)
finalStr += AddNodeToHorizontalString(node, distanceFromStart);
foreach (var child in node.Children)
finalStr += PrintHorizontally(child, level + 1, distanceFromStart + 1);
return finalStr;
}
private static string AddNodeToHorizontalString(Node node, int distanceFromStart)
{
var distanceStr = "";
for (int i = 0; i < distanceFromStart; i++)
distanceStr += "| ";
return $"{distanceStr}{node.Value}\n";
}
public override string ToString() => Value.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment