Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

AlgoExpert Quad Layout Go 14px Sublime Monokai 00:00:0

Our Solution(s) Run Code Your Solutions Run Code

Solution 1 Solution 2 Solution 1 Solution 2 Solution 3

1 // Copyright © 2020 AlgoExpert, LLC. All rights reserved. 1 package main


2 2
3 package main 3 type BST struct {
4 4 Value int
5 import "math" 5
6 6 Left *BST
7 type BST struct { 7 Right *BST
8 value int 8 }
9 9
10 left *BST 10 func (tree *BST) FindClosestValue(target int) int {
11 right *BST 11 // Write your code here.
12 } 12 return -1
13 13 }
14 // Average: O(log(n)) time | O(1) space 14
15 // Worst: O(n) time | O(1) space
16 func (tree *BST) FindClosestValue(target int) int {
17 return tree.findClosestValue(target, math.MaxInt32)
18 }
19
20 func (tree *BST) findClosestValue(target, closest int) int {
21 currentnode := tree
22 for currentnode != nil {
23 if absdiff(target, closest) > absdiff(target, currentnode.value) {
24 closest = currentnode.value
25 }
26 if target < currentnode.value {
27 currentnode = currentnode.left
28 } else if target > currentnode.value {
29 currentnode = currentnode.right
30 } else {
31 break
32 }
33 }

Our Tests Custom Output Submit Code


Run or submit code when you're ready.

You might also like