Python simple solution


  • 0
    D

    Just use a stack and keep track of the number of children visited

    class Solution(object):
        def postorderTraversal(self, root):
            if root is None: return []
            d = []
            out = []
            d.append((root,0))
            while len(d)>0:
                node, k = d.pop()
                if k == 0:
                    d.append((node, k+1))
                    if node.left is not None:
                        d.append((node.left, 0))
                elif k == 1:
                    d.append((node, k+1))
                    if node.right is not None:
                        d.append((node.right, 0))
                else:
                    out.append(node.val)
            return out
    

Log in to reply
 

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