### 270. Closest Binary Search Tree Val

题目： 

<https://leetcode.com/problems/closest-binary-search-tree-value/>



难度 : Easy

最简单的算法是inorder一遍，得到有序的lst，然后O(N) 寻找最靠近的,但是明显不是很高效。

AC代码

```
class Solution(object):
    def closestValue(self, root, target):
        """
        :type root: TreeNode
        :type target: float
        :rtype: int
        """
        lst = []

        def inorder(root):
        	if root:
        		inorder(root.left)
        		lst.append(root.val)
        		inorder(root.right)

        inorder(root)

        close = lst[0]
        diff = abs(target - lst[0])

        for i in lst:
        	if abs(target - i) < diff:
        		close = i
        		diff = abs(target - i )

        return close
```



AC代码，跟binary search tree 寻值一样, loop 一遍树来寻找



```

class Solution(object):
    def closestValue(self, root, target):
        """
        :type root: TreeNode
        :type target: float
        :rtype: int
        """
        close = root.val
        
        while root:
            close = root.val if abs(target - root.val)  < abs(target - close) else close
            root = root.right if root.val < target else root.left
        return close
```

