Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- namespace BinaryTrees
- {
- public class BinaryNode<T>
- {
- public BinaryNode<T> Left { get; set; }
- public BinaryNode<T> Right { get; set; }
- public T Element { get; set; }
- public int Hash { get; }
- public BinaryNode(T element, int hash)
- {
- Element = element;
- Hash = hash;
- }
- public override int GetHashCode()
- {
- var prime = 514229;
- var hash = 1;
- hash *= prime;
- hash ^= Hash;
- return hash;
- }
- }
- public class BinaryTree<T> : IEnumerable<T>
- {
- public BinaryNode<T> Root;
- //Для 2 - ой практики
- public bool Left;
- public Stack<BinaryNode<T>> Stack = new Stack<BinaryNode<T>>();
- //-------------------------------------------------------------
- public void AddToRightOrLeft(BinaryNode<T> root, T element, int hash)
- {
- while (true)
- {
- if (hash - root.Hash < 0)
- {
- if (root.Left == null)
- {
- root.Left = new BinaryNode<T>(element, hash);
- break;
- }
- root = root.Left;
- }
- else
- {
- if (root.Right == null)
- {
- root.Right = new BinaryNode<T>(element, hash);
- break;
- }
- root = root.Right;
- }
- }
- }
- public void Add(T element)
- {
- var hash = element.GetHashCode();
- if (Root == null)
- Root = new BinaryNode<T>(element, hash);
- else
- AddToRightOrLeft(Root, element, hash);
- }
- public BinaryNode<T> FindRoot(T element, out BinaryNode<T> previusRoot)
- {
- var hash = element.GetHashCode();
- var currentRoot = Root;
- previusRoot = null;
- while (currentRoot != null)
- {
- if (hash - currentRoot.Hash == 0) break;
- if (hash - currentRoot.Hash > 0)
- {
- previusRoot = currentRoot;
- currentRoot = currentRoot.Right;
- }
- else if (hash - currentRoot.Hash < 0)
- {
- previusRoot = currentRoot;
- currentRoot = currentRoot.Left;
- }
- }
- return currentRoot;
- }
- public bool Contains(T element)
- {
- BinaryNode<T> root;
- return FindRoot(element, out root) != null;
- }
- //Для 2 - ой практики
- public IEnumerator<T> GetEnumerator()
- {
- var root = Root;
- while (Stack.Count != 0)
- {
- if (Left) Left = false;
- else
- if (root.Left != null)
- {
- Stack.Push(root);
- root = root.Left;
- continue;
- }
- yield return root.Element;
- if (root.Right != null)
- {
- root = root.Right;
- continue;
- }
- root = Stack.Pop();
- Left = true;
- }
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement