Example #1
0
        private int FindClosestValueInBstHelperIterative(NodeBST root, int target, int closest)
        {
            NodeBST currentNode = root;

            while (currentNode != null)
            {
                if (Math.Abs(target - closest) > Math.Abs(target - currentNode.Value))
                {
                    closest = currentNode.Value;
                }
                if (target < currentNode.Value)
                {
                    currentNode = currentNode.Left;
                }
                else if (target > currentNode.Value)
                {
                    currentNode = currentNode.Right;
                }
                else
                {
                    break;
                }
            }
            return(closest);
        }
Example #2
0
 private void InOrderRec(NodeBST root)
 {
     if (root != null)
     {
         InOrderRec(root.Left);
         Console.WriteLine(root.Value);
         InOrderRec(root.Right);
     }
 }
Example #3
0
 // search
 public NodeBST Search(NodeBST rootNode, int item)
 {
     if (rootNode == null || rootNode.Value == item)
     {
         return(rootNode);
     }
     if (root.Value > item)
     {
         return(Search(root.Left, item));
     }
     return(Search(root.Right, item));
 }
Example #4
0
        // recursive method to insert new items in the BST
        private NodeBST InsertRec(NodeBST root, int item)
        {
            // if the tree is empty, return a new node
            if (root == null)
            {
                root = new NodeBST(item);
                return(root);
            }

            // otherwise, recur down the tree
            if (item < root.Value)
            {
                root.Left = InsertRec(root.Left, item);
            }
            else if (item > root.Value)
            {
                root.Right = InsertRec(root.Right, item);
            }

            // return the unchanged node pointer
            return(root);
        }
Example #5
0
 private int FindClosestValueInBstHelper(NodeBST rootNode, int target, int closest)
 {
     if (rootNode == null)
     {
         return(closest);
     }
     if (Math.Abs(target - closest) > Math.Abs(target - rootNode.Value))
     {
         closest = rootNode.Value;
     }
     if (target < rootNode.Value)
     {
         return(FindClosestValueInBstHelper(rootNode.Left, target, closest));
     }
     else if (target > rootNode.Value)
     {
         return(FindClosestValueInBstHelper(rootNode.Right, target, closest));
     }
     else
     {
         return(closest);
     }
 }
Example #6
0
 // method that calls the recursive method InsertRec
 public void Insert(int item)
 {
     root = InsertRec(root, item);
 }
Example #7
0
 public BinarySearchTree()
 {
     root = null;
 }