Simple 5-line iterative Python


  • 0
    Z

    Store all visited values in a dictionary

    def closestValue(self, root, target):
       and = {}
        while root:
            cand[abs(target-root.val)] = root.val      # store value
            root = [root.left, root.right][target > root.val]  # decide go left or right
        return cand[min(cand)]    # return closest value

  • 0
    Z

    Can someone tell me why this method is bad and got down vote?

    A lower space complexity version is:

    def closestValue(self, root, target):
        res = None
        while root:
            if res is None or abs(root.val-target) < abs(res-target):
                res = root.val
            root = root.right if target > root.val else root.left
        return res

  • 0

    Wasn't me who downvoted, but I could imagine it's because your solution doesn't work. Has a syntax error and an indentation error.

    Or maybe someone misunderstood your method and thought it's wrong, or dislikes your style, or dislikes that you use more space than necessary.


  • 0
    Z

    Hey Stefan, thanks for the reply. I do realize that there is a indent problem, but should be easily identified.

    I was just soliciting reasons/comments beyond voting.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.