Binary Tree Postorder Traversal*

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

Example

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

   1
    \
     2
    /
   3

return [3,2,1]

Solution

(1) 首选是搜索向下,如果有左,就不停的把左节点压入占栈,如果左空,则判断右,右不空,把右压入堆栈

(2) 搜索向上,有两种情况, 一种是左节点回到父节点,一种是右节点回到父节点,由于是,左右根,所以如果从左节点回到根,需要由跟节点转移到右节点。

(3) 如果节点在左右节点prev == curr, 或者 curr.right = prev, 右节点返回跟节点,这是就可以按顺序压入列表,并且弹出堆栈。

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param root: The root of binary tree.
    @return: Postorder in ArrayList which contains node values.
    """
    def postorderTraversal(self, root):
        # write your code here
        if root is None:
            return []

        stack = [root]
        postorderResult = []
        prev = None
        curr = None

        while stack:
            curr = stack[-1]
            if prev is None or prev.left == curr or prev.right == curr: # traverse down the tree
                if curr.left:
                    stack.append(curr.left)
                elif curr.right: #非常重要,如果左子树为空的时候,这时候才能考虑是从右面过来的。
                    stack.append(curr.right)
            elif curr.left == prev: # traverse up from the left of the tree then need to go to right 
                if curr.right:
                    stack.append(curr.right)
            else: # the end of node will be added when prev == curr , that means the end.
                postorderResult.append(curr.val)
                stack.pop()
            prev = curr
        return postorderResult

Last updated

Was this helpful?