protected IBinaryNode <T> DeleteNode(IBinaryNode <T> node, T data) { try { if (node == null) { return(node); } if (Comparer.Compare(data, node.GetData()) < 0) { node.SetLeftNode(DeleteNode(node.GetLeftNode(), data)); } else if (Comparer.Compare(data, node.GetData()) > 0) { node.SetRightNode(DeleteNode(node.GetRightNode(), data)); } else { // node with no leaf nodes if (node.GetLeftNode() == null && node.GetRightNode() == null) { return(null); } else if (node.GetLeftNode() == null) { // node with one node (no left node) return(node.GetRightNode()); } else if (node.GetRightNode() == null) { // node with one node (no right node) return(node.GetLeftNode()); } else { // nodes with two nodes // search for min number in right sub tree T minValues = MinValue(node.GetRightNode()); node.SetData(minValues); node.SetRightNode(DeleteNode(node.GetRightNode(), minValues)); } } return(node); } catch (NullReferenceException ex) { throw ex; } }
protected IBinaryNode <T> FindNode(IBinaryNode <T> node, T data) { if (node == null) { return(node); } if (node.GetData().Equals(data)) { return(node); } if (Comparer.Compare(data, node.GetData()) < 0) { return(FindNode(node.GetLeftNode(), data)); } else if (Comparer.Compare(data, node.GetData()) > 0) { return(FindNode(node.GetRightNode(), data)); } else { // node with no leaf nodes if (node.GetLeftNode() == null && node.GetRightNode() == null) { return(null); } else if (node.GetLeftNode() == null) { // node with one node (no left node) return(node.GetRightNode()); } else if (node.GetRightNode() == null) { // node with one node (no right node) return(node.GetLeftNode()); } else { // nodes with two nodes // search for min number in right sub tree T minValues = MinValue(node.GetRightNode()); node.SetData(minValues); node.SetRightNode(FindNode(node.GetRightNode(), minValues)); } return(node); } }
protected T MinValue(IBinaryNode <T> root) { if (root.GetLeftNode() != null) { return(MinValue(root.GetLeftNode())); } return(root.GetData()); }
protected void PrintInOrder(IBinaryNode <T> root) { if (root != null) { PrintInOrder(root.GetLeftNode()); Console.WriteLine(root.GetData().ToString() + " \n"); PrintInOrder(root.GetRightNode()); } }
protected bool RContains(IBinaryNode <T> root, T data) { if (root == null) { return(false); } if (root.GetData().Equals(data)) { return(true); } return(RContains(root.GetLeftNode(), data) || RContains(root.GetRightNode(), data)); }