// public Pop public T Pop() { if (_head == null) { throw new InvalidOperationException(); } var tmp = _head.value; if (_count == 1) { _head = null; _count--; return(tmp); } var parent = GetLastParent(_head, _count - 1); if (parent.right != null) { _head.value = parent.right.value; parent.right = null; } else { _head.value = parent.left.value; parent.left = null; } Pop(_head); _count--; return(tmp); }
// public Add public void Add(T value) { if (_head == null) { _head = new HeapNode <T>(value); } else { var current = GetLastParent(_head, _count); var parent = current; if (current.left == null) { current.left = new HeapNode <T>(value); current = current.left; } else { current.right = new HeapNode <T>(value); current = current.right; } current.parent = parent; Add(current); } _count++; }
// Swap HeapNode values private static void Swap(HeapNode <T> first, HeapNode <T> second) { var tmp = first.value; first.value = second.value; second.value = tmp; }
// Internal Add private void Add(HeapNode <T> current) { if (current == _head || current.CompareTo(current.parent) >= 0) { return; } Swap(current.parent, current); Add(current.parent); }
// Internal Pop private static void Pop(HeapNode <T> current) { if (current.left == null || current.right == null) { return; } if (current.CompareTo(current.left) <= 0 && current.CompareTo(current.right) <= 0) { return; } if (current.left.CompareTo(current.right) < 0) { Swap(current, current.left); Pop(current.left); } else { Swap(current, current.right); Pop(current.right); } }
// using binary string to find the lest parent in tree private static HeapNode <T> GetLastParent(HeapNode <T> node, int value) { var tmp = node; var binary = Convert.ToString(value + 1, 2); binary = binary.Substring(1, binary.Length - 2); var directions = binary.ToCharArray(); foreach (var d in directions) { if (d == '0') { tmp = tmp.left; } else if (d == '1') { tmp = tmp.right; } } return(tmp); }
public int CompareTo(HeapNode <T> node) { return(value.CompareTo(node.value)); }