Tuesday, September 9, 2014

Leetcode: Binary Tree Postorder Traversal @Python

Iterative Solution:
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    def postorderTraversal(self, root):
        rst=[]
        stack=[]
        crt=root
        pre=root
        if crt:
            stack.append(crt)
            while stack:
                crt=stack[-1]
                if not crt.right and not crt.left or (pre==crt.right or pre==crt.left):
                    pre=stack.pop()
                    rst.append(pre.val)
                else :
                    if crt.right:
                        stack.append(crt.right)
                    if crt.left:
                        stack.append(crt.left)
        return rst
Recursive Solution:
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    rst=[]
    def postTvs(self, root):
        if root:
            self.postTvs(root.left)
            self.postTvs(root.right)
            self.rst.append(root.val)
            
    def postorderTraversal(self, root):
        self.rst=[]
        self.postTvs(root)
        return self.rst

No comments :

Post a Comment