Python in-order traversal


  • 0
    C

    class Solution(object):
    def closestKValues(self, root, target, k):
    """
    :type root: TreeNode
    :type target: float
    :type k: int
    :rtype: List[int]
    """
    stack = []
    cur = root
    res = [None] * k
    while stack or cur:
    while cur:
    stack.append(cur)
    cur = cur.left
    s = stack.pop()
    if res[0] is None or abs(s.val - target) <= abs(target - res[0]):
    res = res[1:] + [s.val]
    cur = s.right
    return res


Log in to reply
 

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