Python O(1) SPACE solution


  • 0
    Y
    # 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 postorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            ret = []
            superRoot = TreeNode(-1)
            superRoot.left = root
            cur = superRoot
            prev = None
            while cur is not None:
                if cur.left is None:
                   cur = cur.right
                else:
                   prev = cur.left
                   while prev.right is not None and prev.right != cur:
                       prev = prev.right
                   if prev.right is None:
                      prev.right = cur
                      cur = cur.left
                   else:
                      prevLen = len(ret)
                      prev = cur.left
                      while prev.right != cur:
                        ret.insert(prevLen, prev.val)
                        prev = prev.right
                      ret.insert(prevLen, prev.val)
                      prev.right = None
                      cur = cur.right
            return ret

Log in to reply
 

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