270. Closest Binary Search Tree Value
Posted 我的名字叫周周
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了270. Closest Binary Search Tree Value相关的知识,希望对你有一定的参考价值。
/* * 270. Closest Binary Search Tree Value * 2016-6-25 by Mingyang */ public int closestValue(TreeNode root, double target) { int closest = root.val; double min = Double.MAX_VALUE; while(root!=null) { if( Math.abs(root.val - target) < min ) { min = Math.abs(root.val - target); closest = root.val; } if(target < root.val) { root = root.left; } else if(target > root.val) { root = root.right; } else { return root.val; } } return closest; }
//下面就是recursive的方法,思路很清晰,就是root和左子树或者右子树进行比较大小 public int closestValue1(TreeNode root, double target) { int a = root.val; TreeNode kid = target < a ? root.left : root.right; if (kid == null) return a; int b = closestValue1(kid, target); return Math.abs(a - target) < Math.abs(b - target) ? a : b; }
以上是关于270. Closest Binary Search Tree Value的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 270. Closest Binary Search Tree Value
Leetcode 270: Closest Binary Search Tree Value
[LC] 270. Closest Binary Search Tree Value
270. Closest Binary Search Tree Value - Easy
270. Closest Binary Search Tree Value
LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc