Help! Why the following code receives "Time Limit Exceeded" for input: {}?


  • 0
    L
    class Solution:
    # @param root, a tree node
    # @return a list of integers
    def postorderTraversal(self, root):
        if root == None:
            return []
        
        result = []
        stack = []
        cur = root
        while cur:
            stack.append(cur)
            cur = cur.left
    
        while len(stack):
            cur = stack[-1]
            if cur.left==None and cur.right==None:
                pre = stack.pop()
                result.append(pre.val)
                
            if cur.right:
                if cur.right == pre:
                    pre = stack.pop()
                    result.append(pre.val)
                else:
                    stack.append(cur.right)
                    cur = cur.right
                    while cur.left:
                        cur = cur.left
                        stack.append(cur)
        return result

Log in to reply
 

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