Leetcode 145. Binary Tree Postorder Traversal

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?

从书影的博客抄来的,感觉太难,面试考的机会不大。

 1 class Solution:
 2     # @param root, a tree node
 3     # @return a list of integers
 4     def postorderTraversal(self, root):
 5         if root is None:
 6             return []
 7         stack = [root]
 8         ans = []
 9         pre = None
10         while stack:
11             cur = stack[-1]
12             if pre is None or pre.left == cur or pre.right == cur:
13                 if cur.left:
14                     stack.append(cur.left)
15                 elif cur.right:
16                     stack.append(cur.right)
17             elif pre == cur.left and cur.right:
18                 stack.append(cur.right)
19             else:
20                 ans.append(cur.val)
21                 stack.pop()
22             pre = cur
23         return ans

 

posted @ 2017-05-11 03:24  lettuan  阅读(128)  评论(0编辑  收藏  举报