y12345678904 阅读(23) 评论(0)

题目

这里写图片描述

思路

用栈实现。

代码

# 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_list = []
        stack = []
        lastNode = None
        while stack or root:
            if root:
                stack.append(root)
                root = root.left
            else:
                node = stack[-1]
                if node.right and lastNode != node.right:
                    root = node.right
                else:
                    res_list.append(node.val)
                    lastNode = node
                    stack.pop(-1)
        return res_list