public void Add(dynamic _Data) { //If the Root of the List is not set. if (Root.Data == null) { Root.Data = _Data; return; } else { Current = Root; } //traverse through the tree to the relevant point at which the item should be added while (true) { var temp = Traverse(_Data, Current); //If it is null, we are at a leaf node and we can stop traversing the tree if (temp == null) { break; } Current = temp; } //Check whether we need to add the node to the left or right of if (_Data < Current.Data) { Current.SetLeft(new node(_Data, Current)); } else { Current.SetRight(new node(_Data, Current)); } }
//print Method functions public void Print(node root, int topMargin = 2, int leftMargin = 2) { if (root == null) { return; } int rootTop = Console.CursorTop + topMargin; var last = new List <node>(); var next = root; for (int level = 0; next != null; level++) { var item = new node { Data = next.Data.ToString(" 0 ") }; item.SetLeft(next.GetLeft()); item.SetRight(next.GetRight()); if (level < last.Count) { item.StartPos = last[level].EndPos + 1; last[level] = item; } else { item.StartPos = leftMargin; last.Add(item); } if (level > 0) { item.SetParent(last[level - 1]); if (next == item.GetParent().GetLeft()) { item.GetParent().SetLeft(item); item.EndPos = Math.Max(item.EndPos, item.GetParent().StartPos); } else { item.GetParent().SetRight(item); item.StartPos = Math.Max(item.StartPos, item.GetParent().EndPos); } } next = next.GetLeft() ?? next.GetRight(); for (; next == null; item = item.GetParent()) { Print(item, rootTop + 2 * level); if (--level < 0) { break; } if (item == item.GetParent().GetLeft()) { item.GetParent().StartPos = item.EndPos; next = item.GetParent().GetRight(); } else { if (item.GetParent().GetLeft() == null) { item.GetParent().EndPos = item.StartPos; } else { item.GetParent().StartPos += (item.StartPos - item.GetParent().EndPos) / 2; } } } } Console.SetCursorPosition(0, rootTop + 2 * last.Count - 1); }