题解 |「力扣」第 145 题:二叉树的后序遍历

115 阅读1分钟

摘要:这里给出的是「二叉树的后序遍历」的非迭代的写法,同理可以适用于「二叉树的中序遍历」、「二叉树的前序遍历」。三种遍历都是「深度优先遍历」,因此需要用到「栈」。

Python 代码:

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def postorderTraversal(self, root):
        if not root:
            return []
        stack = [(1, root)]
        res = []
        while stack:
            command, node = stack.pop()
            if command == 0:
                res.append(node.val)
            else:
                # 后序遍历:先左右子树,再自己
                # 入栈顺序:自己、右子树、左子树
                stack.append((0, node))
                if node.right:
                    stack.append((1, node.right))
                if node.left:
                    stack.append((1, node.left))
        return res