边工作边刷题:70天一遍leetcode: day 10-1

Binary Tree Postorder Traversal

这题前面提过,思维方式就是每一层先检查是不是从上到下,然后检查是不是从左边回来的,最后如果是从右边回来的,后续访问。
错误点: 从上到下的时候left和right进栈是if/else的关系

# 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]
        """
        res = []
        if not root: return res
        pre = None
        stk = [root]
        while stk:
            cur = stk[-1]
            if not pre or pre.left==cur or pre.right==cur:
                if cur.left:
                    stk.append(cur.left)
                elif cur.right:
                    stk.append(cur.right)
            elif cur.left==pre:
                if cur.right:
                    stk.append(cur.right)
            else:
                stk.pop()
                res.append(cur.val)
            pre = cur
        return res

posted @ 2016-05-13 10:51  absolute100  阅读(93)  评论(0编辑  收藏  举报