Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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>
- {
- public BinaryNode<T> Root;
- 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;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement