欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LintCode 68. Binary Tree Postorder Traversal

程序员文章站 2024-03-24 14:26:16
...

题目

LintCode 68. Binary Tree Postorder Traversal

思路

非递归后序遍历。

代码

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


class Solution:
    """
    @param: root: A Tree
    @return: Postorder in ArrayList which contains node values.
    """
    def postorderTraversal(self, root):
        # write your code here
        res_list = []
        stack = []
        lastNode = root
        if root: stack.append(root)
        while stack:
          node = stack[-1]
          if node.left and lastNode != node.left and lastNode != node.right:
              stack.append(node.left)
          elif node.right and lastNode != node.right:
              stack.append(node.right)
          else:
              res_list.append(node.val)
              stack.pop(-1)
              lastNode = node
        return res_list