Closest Binary Search Tree Value
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 80 ms)β
| Metric | Value |
|---|---|
| Runtime | 80 ms |
| Memory | 39.4 MB |
| Date | 2021-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β
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |