// Обход в ширину private void Bfs(CustomTreePoint current) { if (current == null) { return; } Queue <CustomTreePoint> queue = new Queue <CustomTreePoint>(); queue.Enqueue(current); while (queue.Count > 0) { var tempNode = queue.Dequeue(); Console.WriteLine(tempNode.Item); if (tempNode.Left != null) { queue.Enqueue(tempNode.Left); } if (tempNode.Right != null) { queue.Enqueue(tempNode.Right); } } }
private List <CustomTreePoint> Bfs() { queue.Clear(); if (head == null) { return(new List <CustomTreePoint>()); } List <CustomTreePoint> values = new List <CustomTreePoint>(); queue.Enqueue(head); CustomTreePoint current = null; while (queue.Count > 0) { current = queue.Dequeue(); values.Add(current); if (current.Left != null) { queue.Enqueue(current.Left); } if (current.Right != null) { queue.Enqueue(current.Right); } } return(values); }
// Обход в глубину private void Dfs(CustomTreePoint current) { Stack <CustomTreePoint> stack = new Stack <CustomTreePoint>(); if (current == null) { return; } stack.Push(current); while (stack.Count > 0) { var tempNode = stack.Pop(); Console.WriteLine(tempNode.Item); if (tempNode.Right != null) { stack.Push(tempNode.Right); } if (tempNode.Left != null) { stack.Push(tempNode.Left); } } }
private void AddBfs(CustomTreePoint head, int item) { queue.Clear(); if (head == null) { return; } queue.Enqueue(head); CustomTreePoint current = null; while (queue.Count > 0) { current = queue.Dequeue(); if (current.Left != null) { queue.Enqueue(current.Left); } else { current.Left = new CustomTreePoint(item); return; } if (current.Right != null) { queue.Enqueue(current.Right); } else { current.Right = new CustomTreePoint(item); return; } } }
private void Print(CustomTreePoint point) { CustomTreePoint current = point; if (current != null) { Console.WriteLine(current.Item); Print(current.Left); Print(current.Right); } }
public void Add(int item) { if (head == null) { head = new CustomTreePoint(item); return; } else { AddBfs(head, item); } }
private int Height(CustomTreePoint point) { int left, right; if (point != null) { left = (point.Left != null) ? Height(point.Left) : 0; right = (point.Right != null) ? Height(point.Right) : 0; return(((left > right) ? left : right) + 1); } return(0); }
public void Add(int item) { CustomTreePoint newItem = new CustomTreePoint(item); if (head == null) { head = newItem; return; } else { CustomTreePoint prev = null; CustomTreePoint current = head; while (true) { prev = current; if (item < current.Item) // Идем налево? { current = current.Left; if (current == null) { prev.Left = newItem; return; } } else if (item > current.Item) // Идем направо? { current = current.Right; if (current == null) { prev.Right = newItem; return; } } else { throw new Exception("Дерево не позволяет вставлять элементы с одинаковым значением."); } } } }
public CustomTree() { head = null; }
public CustomIdealTree() { head = null; queue = new Queue <CustomTreePoint>(); }