【LEETCODE】145-Binary Tree Postorder Traversal

1905 단어 LeetCodepython
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 = None

class 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
        

좋은 웹페이지 즐겨찾기