Both recursive and iterative solution Python with comments


  • 0
    A
    # 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]
            """
            # Basic idea behind this is that we use two stacks
            # One get the element as we traverse and other stores the order
            # So what we want in postorder is that first we have to print left most side then right most side and root
            # so in first stack order will be left right 
            # in second stack pop one element from first stack put into second stack and put left and right for that elem in first stack
            # So basically we are storing element that will print last in second stack first and so forth
            # To get better understanding first draw tree and write down post order traversal check from end to start pattern 
            
            #return self.recursive_traverse(root, [])
            return self.iterative_traverse(root)
        
        def iterative_traverse(self, current):
            if current == None:
                return []
            entry_stack = []
            result_stack = []
            entry_stack.append(current)
            while len(entry_stack) != 0:
                node = entry_stack.pop()
                if node.left:
                    entry_stack.append(node.left)
                if node.right:
                    entry_stack.append(node.right)
                result_stack.append(node.val)
            return(list(reversed(result_stack)))
        
        def recursive_traverse(self, current, result):
            if current:
                self.recursive_traverse(current.left, result)
                self.recursive_traverse(current.right, result)
                result.append(current.val)
                return result
            else:
                return []
                
    

Log in to reply
 

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