-
Notifications
You must be signed in to change notification settings - Fork 75
/
270_Closest_BST_Value
59 lines (51 loc) · 1.73 KB
/
270_Closest_BST_Value
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Leetcode 270: Closest Binary Search Tree Value
Detailed video explanation: https://youtu.be/lIKZB_rhFNM
=================================================
C++:
----
class Solution {
public:
int closestValue(TreeNode* root, double target) {
if(root->val > target && root->left) {
int l = closestValue(root->left, target);
if(abs(l-target) < abs(root->val-target)) return l;
return root->val;
}
if(root->val < target && root->right) {
int r = closestValue(root->right, target);
if(abs(r-target) < abs(root->val-target)) return r;
return root->val;
}
return root->val;
}
};
Java:
----
class Solution {
public int closestValue(TreeNode root, double target) {
if(root.val > target && root.left != null) {
int l = closestValue(root.left, target);
if(Math.abs(l-target) < Math.abs(root.val-target)) return l;
return root.val;
}
if(root.val < target && root.right != null) {
int r = closestValue(root.right, target);
if(Math.abs(r-target) < Math.abs(root.val-target)) return r;
return root.val;
}
return root.val;
}
}
Python3:
-------
class Solution:
def closestValue(self, root: TreeNode, target: float) -> int:
if root.val > target and root.left != None:
l = self.closestValue(root.left, target)
if abs(l-target) < abs(root.val-target): return l
return root.val
if root.val < target and root.right != None:
r = self.closestValue(root.right, target)
if abs(r-target) < abs(root.val-target): return r
return root.val
return root.val