Leetcode 270. Closest Binary Search Tree Value

Mingyu Jeon·2020년 5월 2일
0
post-thumbnail

DFS

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def closestValue(self, root: TreeNode, target: float) -> int:
        self.ans = float(inf)
        def dfs(node, target):
            if node is None: return
            self.ans = node.val if abs(target-node.val) < abs(target-self.ans) else self.ans
            dfs(node.left, target)
            dfs(node.right, target)
        dfs(root, target)
        
        return self.ans

BFS

class Solution:
    def closestValue(self, root: TreeNode, target: float) -> int:
	q = [root, None]
        ans = float(inf)
        while q:
            node = q.pop(0)
            
            if node is None:
                if q: q.append(None)
            else:
                if abs(target-node.val) < abs(target-ans):
                    ans = node.val
                    
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
                    
        return ans

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

0개의 댓글