public void Insert(int i, TreeNode currentNode) { if (currentNode.value == 0) { currentNode.value=i; size++; Console.WriteLine("Inserting the number #" + i + " into the tree"); } else if (i < currentNode.value) { if(currentNode.leftChild==null) currentNode.leftChild = new TreeNode(); Insert(i, currentNode.leftChild); } else if (i > currentNode.value) { if (currentNode.rightChild == null) currentNode.rightChild = new TreeNode(); Insert(i, currentNode.rightChild); } else if (i == currentNode.value) { Console.WriteLine("Duplicate value: " + i + "=("); } }
public BinarySearchTree() { ParentNode = new TreeNode(); while(size < maxsize) { Console.WriteLine("The tree has " + size + " nodes in it atm"); Insert(maxnum.Random(), ParentNode); } Console.WriteLine("Tree Complete! With " + size + " nodes. Booyah!"); Console.WriteLine("Please Enter an integer between 1 and " + maxnum + ", inclusive."); int numVal=-1; //lolwtf do { string input = Console.ReadLine(); try { numVal = Convert.ToInt32(input); } catch (FormatException e) { Console.WriteLine("Input string is not a sequence of digits."); } catch (OverflowException e) { Console.WriteLine("The number cannot fit in an Int32."); } if (numVal > 0 && numVal <= maxnum) { bool success = Search(numVal, ParentNode); if (success == true) Console.WriteLine(numVal + " is in the tree! Hooray!"); else Console.WriteLine(numVal + " isn't in the tree =( It ain't your day..."); } } while (numVal != 0); }
public bool Search(int i, TreeNode currentNode) { bool result = false ; if (currentNode.value == i) { result = true; } else if (i < currentNode.value) { if (currentNode.leftChild == null) return false; result=Search(i, currentNode.leftChild); } else if (i > currentNode.value) { if (currentNode.rightChild == null) return false; result= Search(i, currentNode.rightChild); } return result; }