moonlightshadow123
6/22/2017 - 6:49 AM

145. Binary Tree Postorder Traversal

  1. Binary Tree Postorder Traversal
# 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]
        """
        if root == None:
            return []
        stack = []
        res = []
        to_apd = root
        lastVisit = None
        while to_apd != None or len(stack) != 0:
            if to_apd != None:
                # All the appending work is done here.
                stack.append(to_apd)
                to_apd = to_apd.left
            else:
                n = stack[-1]
                if n.right != None and n.right != lastVisit:
                    # If n has a right node and it is not visited, append the right node.
                    to_apd = n.right
                else:
                    # Else, consume n
                    del stack[-1]
                    res.append(n.val)
                    lastVisit = n
        return res
# You can simply reverse the preoder of the tree to get the post oder.

# 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]
        """
        if root == None:
            return []
        stack = [root]
        res = []
        while len(stack) != 0:
            curNode = stack[-1]
            del stack[-1]
            res.append(curNode.val)
            if curNode.left:
                stack.append(curNode.left)
            if curNode.right:
                stack.append(curNode.right)
        return res[::-1]

https://leetcode.com/problems/binary-tree-postorder-traversal/#/description

Given a binary tree, return the postorder traversal of its nodes' values.

For example: Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?