From 6b4894c49ff7f025c99aa47f916cc8e19a9047a6 Mon Sep 17 00:00:00 2001 From: Ching Date: Sun, 23 Jan 2022 20:51:26 +0800 Subject: [PATCH] =?UTF-8?q?feat(leetcode):=20145.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 145.二叉树的后序遍历 Signed-off-by: Ching --- 145.二叉树的后序遍历.py | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 145.二叉树的后序遍历.py diff --git a/145.二叉树的后序遍历.py b/145.二叉树的后序遍历.py new file mode 100644 index 0000000..13bec0a --- /dev/null +++ b/145.二叉树的后序遍历.py @@ -0,0 +1,48 @@ +# +# @lc app=leetcode.cn id=145 lang=python3 +# +# [145] 二叉树的后序遍历 +# + +# @lc code=start +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + + +from typing import Optional, List + +from utils import * + + +class Solution: + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + res = [] + stack = [] + if not root: + return [] + stack.append(root) + while stack: + node = stack[-1] + if node: + stack.pop() + stack.append(node) + stack.append(None) + if node.right: + stack.append(node.right) + if node.left: + stack.append(node.left) + else: + stack.pop() + node = stack.pop() + res.append(node.val) + return res + + +s = Solution() +s.postorderTraversal(generate_tree([1, None, 2, 3])) + +# @lc code=end