public static int FindClosestValueInBst(ClosestValueBST tree, int target, double closest) { ClosestValueBST currentNode = tree; 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((int)closest); }
// Average: O(log(n)) time | O(1) space // Worst: O(n) time | O(1) space public static int FindClosestValueInBst(ClosestValueBST tree, int target) { return(FindClosestValueInBst(tree, target, Int32.MaxValue)); }