【LEETCODE】145-Binary Tree Postorder Traversal

来源:互联网 发布:直通车关键字优化 编辑:程序博客网 时间:2024/05/01 12:23

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

For example:

Given binary tree {1,#,2,3},

   1

    \

     2

    /

   3


return [3,2,1].

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


参考:

http://bookshadow.com/weblog/2015/01/19/leetcode-binary-tree-postorder-traversal/


# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def postorderTraversal(self, root):        """        :type root: TreeNode        :rtype: List[int]        """                if root is None:            return []                ans = []                        #返回答案        stack = [root]                  #stack记录cur的轨迹        pre = None                      #pre跟随cur的脚步                while stack:                        cur = stack[-1]                        if pre is None or pre.left==cur or pre.right==cur:       #当pre是cur的parent时,cur优先向左child走,没有左child再走右child                if cur.left:                    stack.append(cur.left)                elif cur.right:                    stack.append(cur.right)            elif pre==cur.left and cur.right:                        #当pre是cur的左child时,并且cur有右child时,cur继续向右走                stack.append(cur.right)            else:                                       #当pre==cur时,或者pre==cur.left但是cur.right不存在时,                ans.append(cur.val)                     #ans记录cur.val                stack.pop()                             #stack向上跳一层                        pre=cur           <span style="font-family: Arial, Helvetica, sans-serif;">                     #pre跟随cur的脚步</span>                return ans        


0 0