/// <summary> /// PostOrder traversal the tree, left -> right -> root /// </summary> /// <param name="currentNode"></param> /// <returns></returns> public IEnumerable <Node <T, U> > PostOrder(Node <T, U> currentNode) { if (currentNode != null) { //recursively call left child if (currentNode.HasLeftChild()) { foreach (var node in PostOrder(currentNode.LeftChild)) { yield return(node); } } //recursively call right child if (currentNode.HasRightChild()) { foreach (var node in PostOrder(currentNode.RightChild)) { yield return(node); } } //parent yield return(currentNode); } }
private void _Remove(Node <T, U> currentNode) { //is leaf if (currentNode.IsLeaf()) { //is left child if (currentNode.IsLeftChild()) { currentNode.Parent.LeftChild = null; } //is right child else { currentNode.Parent.RightChild = null; } } //is not leaf else { //is left child if (currentNode.IsLeftChild()) { //has only left child if (currentNode.HasLeftChild() && !currentNode.HasRightChild()) { currentNode.Parent.LeftChild = currentNode.LeftChild; currentNode.LeftChild.Parent = currentNode.Parent; } //has only right child if (!currentNode.HasLeftChild() && currentNode.HasRightChild()) { currentNode.Parent.LeftChild = currentNode.RightChild; currentNode.RightChild.Parent = currentNode.Parent; } //has both children else { } } //is right child else { } } }
private void _Put(T key, U value, Node <T, U> currentNode, bool changeable = false) { //if key less than currentNode, _put to left if (key.CompareTo(currentNode.Key) < 0) { if (currentNode.HasLeftChild()) { _Put(key, value, currentNode.LeftChild); } else { currentNode.LeftChild = new Node <T, U>(key, value, parent: currentNode); } } else if (key.CompareTo(currentNode.Key) > 0) //_put to right { if (currentNode.HasRightChild()) { _Put(key, value, currentNode.RightChild); } else { currentNode.RightChild = new Node <T, U>(key, value, parent: currentNode); } } else //equals to current key { if (!changeable) { throw new Exception("The Id already exists!"); } else { currentNode.Payload = value; } } }