题目:
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
递归。用全局变量保存当前最接近的节点值。
C++版:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int closestValue(TreeNode* root, double target) { if(root->val == target) return target; double cur = abs(root->val - target); if(cur < curM) { curM = cur; rootV = root->val; } if(root->val < target) { if(root->right != NULL) return closestValue(root->right, target); else return rootV; } else { if(root->left != NULL) return closestValue(root->left, target); else return rootV; } } private: double rootV = INT_MAX; double curM = std::numeric_limits<double>::max(); };
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int closestValue(TreeNode root, double target) { if(root.val == target) return root.val; double cur = Math.abs(root.val - target); if(cur < curM) { rootV = root.val; curM = cur; } if(root.val > target) { if(root.left != null) return closestValue(root.left, target); else return rootV; } else { if(root.right != null) return closestValue(root.right, target); else return rootV; } } private int rootV = Integer.MAX_VALUE; private double curM = Double.MAX_VALUE; }
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None import sys class Solution(object): def __init__(self): self.v = sys.maxint self.curM = sys.maxint def closestValue(self, root, target): """ :type root: TreeNode :type target: float :rtype: int """ if root.val == target: return root.val cur = abs(root.val - target) if cur < self.curM: self.curM = cur self.v = root.val if root.val > target: if root.left != None: return self.closestValue(root.left, target) else: return self.v else: if root.right != None: return self.closestValue(root.right, target) else: return self.v