python iterative solution


  • 0
    L
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
    
        def inorderSuccessor(self, root, p):
            """
            :type root: TreeNode
            :type p: TreeNode
            :rtype: TreeNode
            """
            if not root:
                return None
    
            stack = []
            node = root
            while node:
                stack.append(node)
                node = node.left
    
            found = False
            while len(stack) > 0:
                n = stack.pop()
                if found:
                    return n
                if n.val == p.val:
                    found = True
                if n.right:
                    n = n.right
                    while n:
                        stack.append(n)
                        n = n.left
                
            return None 
            
    

Log in to reply
 

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