public void Insert(BinaryNode <T> currNode, T key) { if (key.CompareTo(currNode.GetElement()) < 0) { //Lower than if (currNode.GetLeft() != null) { Insert(currNode.GetLeft(), key); } else { currNode.SetLeft(new BinaryNode <T>(key)); } } else { //Greater (or equal) if (currNode.GetRight() != null) { Insert(currNode.GetRight(), key); } else { currNode.SetRight(new BinaryNode <T>(key)); } } }
private void PrintInOrder(BinaryNode <T> node) { if (node != null) { PrintInOrder(node.GetLeft()); Console.WriteLine(node.GetElement().ToString()); PrintInOrder(node.GetRight()); } }
public void Remove(T x) { if (Root == null) { return; } // Traverse tree until we find the desired node; And remember prev node so we can remove node with element X later BinaryNode <T> lookup = Root; BinaryNode <T> prev = Root; while (lookup.GetElement().CompareTo(x) != 0) { if (lookup.GetElement().CompareTo(x) < 0) { if (lookup.GetLeft() == null) { return; // x not in tree } prev = lookup; lookup = lookup.GetLeft(); } else if (lookup.GetElement().CompareTo(x) > 0) { if (lookup.GetRight() == null) { return; // x not in tree } prev = lookup; lookup = lookup.GetRight(); } } // Remove desired node from reference if (prev.GetRight().Equals(lookup)) { prev.SetRight(null); } else if (prev.GetLeft().Equals(lookup)) { prev.SetLeft(null); } }
public T FindMin() { if (Root == null) { return(default(T)); } BinaryNode <T> currNode = Root; while (currNode.GetLeft() != null) { currNode = currNode.GetLeft(); } return(currNode.GetElement()); }