Given a non-empty binary search tree and a target value, find the value in the BST, which is closest to the target. Note:given target value is a floating point. Guaranteed to has only one unique value in the BST, which 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 */Ten Public classSolution { One Public intClosestvalue (TreeNode root,Doubletarget) { A if(Root = =NULL)returnInteger.min_value; -Arraylist<integer> PreVal =NewArraylist<integer>(); -arraylist<integer> res =NewArraylist<integer>(); the Helper (root, Target, PreVal, res); - if(res.size () = = 0) { -Res.add (Preval.get (0)); - } + returnRes.get (0); - } + A Public voidHelper (TreeNode root,DoubleTarget, arraylist<integer> PreVal, arraylist<integer>Res) { at if(Root = =NULL)return; - Helper (Root.left, Target, PreVal, res); - if(preval.size () = = 0) { - Preval.add (root.val); - } - Else if(Root.val >=target) { in if(Res.size () ==0) -Res.add (Math.Abs (Double) (Preval.get (0)-target)) <math.abs ((Double) (Root.val-target))? Preval.get (0): root.val); to return; + } - Else { thePreval.set (0, root.val); * } $ Helper (root.right, Target, PreVal, res);Panax Notoginseng } -}
Leetcode:closest Binary Search Tree Value