Last active
March 23, 2021 15:52
-
-
Save tuliopaim/f564156ccc42de2b770110d9cc981851 to your computer and use it in GitHub Desktop.
Simple Char Tree in C#
This file contains hidden or 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; | |
| 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