Closest Binary Search Tree Value -- LeetCode
2016-08-15 02:54
405 查看
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.
思路:递归求解。因为是二叉搜索树,我们不需要遍历所有的节点,通过prune来提高速度。
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.
思路:递归求解。因为是二叉搜索树,我们不需要遍历所有的节点,通过prune来提高速度。
/** * 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) { int res = root->val; if (root->left != NULL && (double)res > target) { int leftRes = closestValue(root->left, target); res = abs(res - target) < abs(leftRes - target) ? res : leftRes; } if (root->right != NULL && (double)res < target) { int rightRes = closestValue(root->right, target); res = abs(res - target) < abs(rightRes - target) ? res : rightRes; } return res; } };
相关文章推荐
- LeetCode 270: Closest Binary Search Tree Value
- [Leetcode]Closest Binary Search Tree Value II
- [Leetcode]Closest Binary Search Tree Value
- Leetcode NO.270 Closest Binary Search Tree Value
- Leetcode 270. Closest Binary Search Tree Value (cpp)
- [LeetCode] Closest Binary Search Tree Value 最近的二分搜索树的值
- [leetcode 270] Closest Binary Search Tree Value
- Leetcode 272. Closest Binary Search Tree Value II (Hard) (cpp)
- LeetCode "Closest Binary Search Tree Value II"
- LeetCode 272. Closest Binary Search Tree Value II
- Leetcode 270 Closest Binary Search Tree Value
- Leetcode 272. Closest Binary Search Tree Value II
- [Leetcode] 272. Closest Binary Search Tree Value II 解题报告
- Leetcode: Closest Binary Search Tree Value II
- LeetCode-Closest Binary Search Tree Value
- Leetcode: Closest Binary Search Tree Value
- [LeetCode] 270. Closest Binary Search Tree Value 最近的二叉搜索树的值
- 【LeetCode】270.Closest Binary Search Tree Value(Easy)解题报告
- [LeetCode] 272. Closest Binary Search Tree Value II 最近的二叉搜索树的值 II
- [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二