码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Closest Binary Search Tree Value

时间:2015-12-24 10:30:24      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int closestValue(TreeNode root, double target) {
12         if (root == null) return Integer.MIN_VALUE;
13         ArrayList<Integer> preVal = new ArrayList<Integer>();
14         ArrayList<Integer> res = new ArrayList<Integer>();
15         helper(root, target, preVal, res);
16         if (res.size() == 0) {
17             res.add(preVal.get(0));
18         }
19         return res.get(0);
20     }
21     
22     public void helper(TreeNode root, double target, ArrayList<Integer> preVal, ArrayList<Integer> res) {
23         if (root == null) return;
24         helper(root.left, target, preVal, res);
25         if (preVal.size() == 0) {
26             preVal.add(root.val);
27         }
28         else if (root.val >= target) {
29             if (res.size()==0)
30                 res.add(Math.abs((double)(preVal.get(0)-target))<Math.abs((double)(root.val-target))? preVal.get(0) : root.val);
31             return;
32         }
33         else {
34             preVal.set(0, root.val);
35         }
36         helper(root.right, target, preVal, res);
37     }
38 }

 

Leetcode: Closest Binary Search Tree Value

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5072117.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!