Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

270. Closest Binary Search Tree Value #128

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

/**

public class Solution { public int closestValue(TreeNode root, double target) { if(root.val == target) { return root.val; } else if(target > root.val) { // if target is larger than root, // the answer can only be // 1. root itself // 2. inside the right sub tree return root.right == null ? root.val : (Math.abs(target-root.val) < Math.abs(target-closestValue(root.right, target)) ? root.val: closestValue(root.right, target)); } else { // if target is smaller than root, // the answer can only be // 1. root itself // 2. inside the left sub tree. return root.left == null ? root.val : (Math.abs(target-root.val) < Math.abs(target-closestValue(root.left, target)) ? root.val: closestValue(root.left, target)); } } }

Shawngbk commented 7 years ago

image