Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit001695a

Browse files
authored
Update Closest Binary Search Tree Value.java
1 parentb2188e0 commit001695a

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

‎Easy/Closest Binary Search Tree Value.java

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,35 @@
44
* int val;
55
* TreeNode left;
66
* TreeNode right;
7-
* TreeNode(int x) { val = x; }
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
814
* }
915
*/
1016
classSolution {
1117
publicintclosestValue(TreeNoderoot,doubletarget) {
12-
int[]ans = {0};
13-
doubleminDiff =Double.MAX_VALUE;
14-
helper(root,target,ans,minDiff);
15-
returnans[0];
16-
}
18+
double[]result = {Double.MAX_VALUE, -1};
19+
helper(root,target,result);
20+
return (int)result[1];
21+
}
1722

18-
privatevoidhelper(TreeNoderoot,doubletarget,int[]ans,doubleminDiff) {
23+
privatevoidhelper(TreeNoderoot,doubletarget,double[]result) {
1924
if (root ==null) {
2025
return;
2126
}
22-
if (Math.abs(root.val -target) <minDiff) {
23-
minDiff =Math.abs(root.val -target);
24-
ans[0] =root.val;
25-
}
26-
if (root.val <target) {
27-
helper(root.right,target,ans,minDiff);
27+
doublediff =Math.abs(root.val -target);
28+
if (diff <=result[0]) {
29+
result[0] =diff;
30+
result[1] =root.val;
2831
}
29-
else {
30-
helper(root.left,target,ans,minDiff);
32+
if (root.val >target) {
33+
helper(root.left,target,result);
34+
}else {
35+
helper(root.right,target,result);
3136
}
3237
}
3338
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp