LeetCode每週一題之145. Binary Tree Postorder Traversal(2018.07.26)

題目:

 

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

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

代碼:

# 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]
        """
        s = []
        list=[]
        s.append(root)
        cur = root
        pre = None
        p=root
        if root:
            while len(s)!= 0:
                cur=s[-1]
                if ( cur.left==None and cur.right==None ) or ( pre!=None and ( pre==cur.right or pre==cur.left ) ):
                    list.append(cur.val)
                    pre=cur
                    s.pop()
                else:
                    if cur.right!=None:
                        s.append(cur.right)
                    if cur.left!=None:
                        s.append(cur.left)
        return list
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章