示例#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);
        }
示例#2
0
 private void InOrderRec(NodeBST root)
 {
     if (root != null)
     {
         InOrderRec(root.Left);
         Console.WriteLine(root.Value);
         InOrderRec(root.Right);
     }
 }
示例#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));
 }
示例#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);
        }
示例#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);
     }
 }
示例#6
0
 // method that calls the recursive method InsertRec
 public void Insert(int item)
 {
     root = InsertRec(root, item);
 }
示例#7
0
 public BinarySearchTree()
 {
     root = null;
 }