Skip to main content

Closest Binary Search Tree Value

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 80 ms)​

MetricValue
Runtime80 ms
Memory39.4 MB
Date2021-11-22
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public int ClosestValue(TreeNode root, double target) {
var current = root;
double least = (double) Int32.MaxValue;
int result = 0;
while(current != null)
{
double newLeast = Math.Abs((double)current.val - target);
if(newLeast < least)
{
result = current.val;
least = newLeast;
}

if(target > current.val)
{
current = current.right;
}
else
{
current = current.left;
}
}

return result;
}
}
πŸ“œ 1 more C# submission(s)

Submission (2021-11-22) β€” 96 ms, 39.7 MB​

/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public int ClosestValue(TreeNode root, double target) {
if(root.left == null && root.right == null)
{
return root.val;
}

var current = root;
double least = (double) Int32.MaxValue;
int currentVal = 0;
while(current != null)
{
double newLeast = Math.Abs((double)current.val - target);
if(newLeast < least)
{
currentVal = current.val;
least = newLeast;
}

if(target > current.val)
{
current = current.right;
}
else
{
current = current.left;
}
}

return currentVal;
}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed