Python iterative solution returning early

  • 0

    I used iterative method to traverse the BST tree. This traversal method is swift and can be used to do post-order, pre-order and in-order traversal by changing only the order of () in stack.extend([(1, p[1].right), (0, p[1]), (1, p[1].left)]) as you can refer in this article I posted below another problem.

    class Solution(object):
        def closestValue(self, root, target):
            if root is None:
                return None
            minDiff = None
            minV = None
            stack = [(1, root)]
            while stack:
                p = stack.pop()
                if not p[1]: continue
                if p[0] == 1:
                    stack.extend([(1, p[1].right), (0, p[1]), (1, p[1].left)])  
                    num = p[1].val
                    if minDiff is None:
                        minDiff = abs(num - target)
                        minV = num     
                        if abs(num - target) < minDiff:
                            minDiff = abs(num - target)
                            minV = num
            return minV

Log in to reply

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