From 9edc7aa01df2f652a170435870747a0896b0d83e Mon Sep 17 00:00:00 2001 From: charon2121 <66763177+charon2121@users.noreply.github.com> Date: Wed, 19 May 2021 08:28:50 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20144.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=89=8D=E5=BA=8F=E9=81=8D=E5=8E=86=20python?= =?UTF-8?q?3=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新 145.二叉树的后序遍历 python3版本 更新 94.二叉树的中序遍历 python3版本 --- problems/二叉树的迭代遍历.md | 62 ++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index 2647616b..be2456de 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -160,6 +160,68 @@ Java: Python: +```python3 +# 前序遍历-迭代-LC144_二叉树的前序遍历 +class Solution: + def preorderTraversal(self, root: TreeNode) -> List[int]: + # 根结点为空则返回空列表 + if not root: + return [] + stack = [root] + result = [] + while stack: + node = stack.pop() + # 中结点先处理 + result.append(node.val) + # 右孩子先入栈 + if node.right: + stack.append(node.right) + # 左孩子后入栈 + if node.left: + stack.append(node.left) + return result + +# 中序遍历-迭代-LC94_二叉树的中序遍历 +class Solution: + def inorderTraversal(self, root: TreeNode) -> List[int]: + if not root: + return [] + stack = [] # 不能提前将root结点加入stack中 + result = [] + cur = root + while cur or stack: + # 先迭代访问最底层的左子树结点 + if cur: + stack.append(cur) + cur = cur.left + # 到达最左结点后处理栈顶结点 + else: + cur = stack.pop() + result.append(cur.val) + # 取栈顶元素右结点 + cur = cur.right + return result + +# 后序遍历-迭代-LC145_二叉树的后序遍历 +class Solution: + def postorderTraversal(self, root: TreeNode) -> List[int]: + if not root: + return [] + stack = [root] + result = [] + while stack: + node = stack.pop() + # 中结点先处理 + result.append(node.val) + # 左孩子先入栈 + if node.left: + stack.append(node.left) + # 右孩子后入栈 + if node.right: + stack.append(node.right) + # 将最终的数组翻转 + return result[::-1] +``` Go: