Closest Binary Search Tree Value
给一个 bst和一个double, 问你能不能找到一个值,和target的值最相近.
很naive的解法.在二叉遍历的同时, 记录当前节点值合给的值的差.
public int closestValue(TreeNode root, double target) { int res = root.val; while(root != null){ if(Math.abs(root.val - target) < Math.abs(res - target)) res = root.val; if(root.val < target) root = root.right; else root = root.left; } return res; }
Leave A Comment