Blog Archive

Thursday, August 14, 2014

Binary Tree Preorder Inorder Postorder Traversal solution.

class Solution:
    def preorderTraversal(self, root):
        #option 1: recursion version
        #def recursion(T): return [] if T is None else [T.val] + recursion(T.left) + recursion(T.right)
        #return recursion(root)
        # option 2: iterative version
       
        res, stack = [], [root]
        if root:
            while stack:
                current=stack.pop()
                res.append(current.val)
                if current.right: stack.append(current.right)
                if current.left:  stack.append(current.left)
        return res

    def inorderTraversal(self, root):
        #option 1: recursion version
        #def recursion(T): return [] if T is None else recursion(T.left) + [T.val] + recursion(T.right)
        #return recursion(root)
        # option 2: iterative version

        res, stack, current = [], [], root
        while stack or current:
            if current:
                stack.append(current)
                current = current.left
            else:
                parent = stack.pop()
                res.append(parent.val)
                current = parent.right
        return res

    def postorderTraversal(self, root):
        #option 1: recursion version
        #def recursion(T): return [] if T is None else recursion(T.left) + recursion(T.right) + [T.val]
        #return recursion(root)
        # option 2: iterative version  
    # http://www.cnblogs.com/zuoyuan/p/3720846.html

    res, stack, prev = [], [root], None
    if root:
       while stack:
           curr=stack[-1]
           if (curr.left == None and curr.right == None) or (prev and (prev == curr.left or prev == curr.right)):
               res.append(curr.val)
               stack.pop()
               prev=curr
           else:
               if curr.right: stack.append(curr.right)
               if curr.left: stack.append(curr.left)
    return res

No comments:

Post a Comment