Python iterative solution


  • 1
    G
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param {TreeNode} root
        # @return {integer[]}
        def postorderTraversal(self, root):
            if not root:
                return []
    
            result, queue = [], [(root, False)]
            while queue:
                curNode, visited = queue.pop()
                if curNode:
                    if visited:
                        result.append(curNode.val)
                    else:
                        queue.append((curNode, True))
                        queue.append((curNode.right, False))
                        queue.append((curNode.left, False))
    
            return result

  • 0
    H

    elegant solution


Log in to reply
 

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