FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/270_Closest_Binary_Search_Tree_Value.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
270_Closest_Binary_Search_Tree_Value.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
36 lines (28 loc) · 1014 Bytes
Breadcrumbs
leetcode
/
java
/
270_Closest_Binary_Search_Tree_Value.java
Copy path
File metadata and controls
36 lines (28 loc) · 1014 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
https://leetcode.com/problems/closest-binary-search-tree-value/
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Update closest if current node is closer to target then previous closest. Go left or right according to whether
target is above or below node. Values in other subtree cannot be closes than current node.
Time - O(n), height of tree
Space - O(1)
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public
class
Solution
{
public
int
closestValue
(
TreeNode
root
,
double
target
) {
int
closest
=
root
.
val
;
// assumes root is not null
while
(
root
!=
null
) {
if
(
Math
.
abs
(
root
.
val
-
target
) <
Math
.
abs
(
closest
-
target
))
closest
=
root
.
val
;
root
=
target
>
root
.
val
?
root
=
root
.
right
:
root
.
left
;
}
return
closest
;
}
}
Back
|
FazBrowse Home
|
New Git URL