# Solution

The main objective here is to find the closest number to the given target value.

`public class BST{        public BST(int value)        {            this.value = value;        }          public int value;        public BST left;        public BST right;     }`
1. We will create a function that takes the currentTree, targetValue and the closestNode.
`private int GetClosestValue(BST tree, int target, int closest){}`
`int answer = GetClosestValue(tree, 12, 10);`
`private int GetClosestValue(BST tree, int target, int closest){    if (Math.Abs(target - closest) > Math.Abs(target - tree.value))    {        closest = tree.value;    }}`
1. So if currentNodeValue > targetValue, Move Left.
2. But if currentNodeValue < targetValue, Move Right.
3. But if currentNodeValue == targetValue, that means the targetValue is actually present in our binary node. In that case return the value itself.
`private int GetClosestValue(BST tree, int target, int closest){     if (Math.Abs(target - tree.value) < Math.Abs(target - closest))     {                closest = tree.value;     }     if (tree.value > target && tree.left != null)     {         return GetClosestValue(tree.left, target, closest);     }     else if (tree.value < target && tree.right != null)     {          return GetClosestValue(tree.right, target, closest);     }     else     {          return closest;     }}`

# Time and Space Complexity?

## Worst Case: Skewed Binary Tree. (Worst Case Scenario)
`private int GetClosestValue(BST tree, int target, int closest){    // Time Complexity    //           - Average Case: O(log n)    //           - Worst Case: O(n)    // Space Complexity    //           - Average Case: O(1)    //           - Worst Case: O(1)    while (true)    {       if (Math.Abs(target - tree.value)<Math.Abs(target - closest))       {          closest = tree.value;       }       if (tree.value > target && tree.left != null)       {          tree = tree.left;       }       else if (tree.value < target && tree.right != null)       {          tree = tree.right;       }       else       {          return closest;       }    }}`

--

--