首页 > 其他 > 详细

[LeetCode] Closest Binary Search Tree Value

时间:2015-08-27 14:59:53      阅读:157      评论:0      收藏:0      [点我收藏+]

Well, this problem can be solved easily using recursion: just find the closest value in the left and right subtrees and compare them with root -> val. The code is as follows.

 1 class Solution {
 2 public:
 3     int closestValue(TreeNode* root, double target) {
 4         if (!root) return INT_MAX;
 5         if (!(root -> left) && !(root -> right)) return root -> val;
 6         int left = closestValue(root -> left, target);
 7         int right = closestValue(root -> right, target);
 8         double td = abs(root -> val - target), ld = abs(left - target), rd = abs(right - target);
 9         if (td < ld) return td < rd ? root -> val : right;
10         else return ld < rd ? left : right;
11     }
12 };

Notice that in the above code the properties of BST have not been used. So, what do you think? Well, the above code can be extended to Closest Binary Tree Value if this problem is published in the future :-) Well, Stefan posts several solutions (including a shorter C++ one) in 4 languages here. So, refer to them and get more fun :-)

[LeetCode] Closest Binary Search Tree Value

原文:http://www.cnblogs.com/jcliBlogger/p/4763200.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!