Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Generics.BinaryTrees
- {
- public class BinaryTree<T> : IEnumerable<T> where T : IComparable, new()
- {
- private BinaryNode<T> Top;
- public BinaryNode<T> Left => Top.Left;
- public BinaryNode<T> Right => Top.Right;
- public T Value => Top.Value;
- public BinaryTree(T value)
- {
- Top = new BinaryNode<T>(value);
- }
- public BinaryTree()
- {
- Top = null;
- }
- private void AddHelper(ref BinaryNode<T> node, T value)
- {
- if (node == null)
- {
- var newNode = new BinaryNode<T>(value);
- node = newNode;
- return;
- }
- if (value.CompareTo(node.Value) <= 0)
- {
- AddHelper(ref node.Left, value);
- return;
- }
- if (value.CompareTo(node.Value) > -1)
- {
- AddHelper(ref node.Right, value);
- return;
- }
- }
- public void Add(T value)
- {
- AddHelper(ref Top,value);
- }
- public IEnumerator<T> GetEnumerator()
- {
- if (Top == null) yield break;
- var stack = new Stack<BinaryNode<T>>();
- var node = Top;
- while (stack.Count > 0 || node != null)
- {
- if (node == null)
- {
- node = stack.Pop();
- yield return node.Value;
- node = node.Right;
- }
- else
- {
- stack.Push(node);
- node = node.Left;
- }
- }
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
- public class BinaryNode<T> where T : IComparable
- {
- public T Value;
- public BinaryNode(T value)
- {
- Value = value;
- }
- public BinaryNode<T> Left;
- public BinaryNode<T> Right;
- }
- public class BinaryTree
- {
- public static BinaryTree<T> Create<T>(params T[] items) where T : IComparable, new()
- {
- var result = new BinaryTree<T>();
- foreach (var item in items)
- {
- result.Add(item);
- }
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement