Leetcode: 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.
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.
Inorder Traversal:
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 }
Recursion: (转)根据二叉树的性质,我们知道当遍历到某个根节点时,最近的那个节点要么是在子树里面,要么就是根节点本身。所以我们根据这个递归,返回子树中最近的节点,和根节点中更近的那个就行了。
1 public class Solution { 2 public int closestValue(TreeNode root, double target) { 3 // 选出子树的根节点 4 TreeNode kid = target < root.val ? root.left : root.right; 5 // 如果没有子树,也就是递归到底时,直接返回当前节点值 6 if(kid == null) return root.val; 7 // 找出子树中最近的那个节点 8 int closest = closestValue(kid, target); 9 // 返回根节点和子树最近节点中,更近的那个节点 10 return Math.abs(root.val - target) < Math.abs(closest - target) ? root.val : closest; 11 } 12 }
Iteration: (转)
1 public class Solution { 2 public int closestValue(TreeNode root, double target) { 3 int closest = root.val; 4 while(root != null){ 5 // 如果该节点的离目标更近,则更新到目前为止的最近值 6 closest = Math.abs(closest - target) < Math.abs(root.val - target) ? closest : root.val; 7 // 二叉搜索 8 root = target < root.val ? root.left : root.right; 9 } 10 return closest; 11 } 12 }