Python solution with detailed explanation


  • 0
    G

    Solution

    Binary Tree Postorder Traversal https://leetcode.com/problems/binary-tree-postorder-traversal/?tab=Description

    Algorithm

    • It is trivial to code up preorder traversal using a stack.
    • There is a solid trick involved here: Pre-order is VLR. Pre-Order variant will be VRL.
    • Now reverse that variant: LRV - which is Post Order.
    class Solution(object):
        def postorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            result = []
            if root == None:
                return []
            st = [root]
            while len(st) > 0:
                x = st.pop()
                if x.left:
                    st.append(x.left)
                if x.right:
                    st.append(x.right)
                result.append(x)
            return map(lambda x:x.val, reversed(result))
    

Log in to reply
 

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