Leetcode-145題:Binary Tree Postorder Traversal

weixin_33751566發表於2016-09-26

題目

非遞迴後序遍歷

程式碼

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

相關文章