Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9edc7aa

Browse files
更新 144.二叉树的前序遍历 python3版本
更新 145.二叉树的后序遍历 python3版本 更新 94.二叉树的中序遍历 python3版本
1 parent fc09458 commit 9edc7aa

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

‎problems/二叉树的迭代遍历.md‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,68 @@ Java:
160160
161161
162162
Python:
163+
```python3
164+
# 前序遍历-迭代-LC144_二叉树的前序遍历
165+
class Solution:
166+
def preorderTraversal(self, root: TreeNode) -> List[int]:
167+
# 根结点为空则返回空列表
168+
if not root:
169+
return []
170+
stack = [root]
171+
result = []
172+
while stack:
173+
node = stack.pop()
174+
# 中结点先处理
175+
result.append(node.val)
176+
# 右孩子先入栈
177+
if node.right:
178+
stack.append(node.right)
179+
# 左孩子后入栈
180+
if node.left:
181+
stack.append(node.left)
182+
return result
183+
184+
# 中序遍历-迭代-LC94_二叉树的中序遍历
185+
class Solution:
186+
def inorderTraversal(self, root: TreeNode) -> List[int]:
187+
if not root:
188+
return []
189+
stack = [] # 不能提前将root结点加入stack中
190+
result = []
191+
cur = root
192+
while cur or stack:
193+
# 先迭代访问最底层的左子树结点
194+
if cur:
195+
stack.append(cur)
196+
cur = cur.left
197+
# 到达最左结点后处理栈顶结点
198+
else:
199+
cur = stack.pop()
200+
result.append(cur.val)
201+
# 取栈顶元素右结点
202+
cur = cur.right
203+
return result
204+
205+
# 后序遍历-迭代-LC145_二叉树的后序遍历
206+
class Solution:
207+
def postorderTraversal(self, root: TreeNode) -> List[int]:
208+
if not root:
209+
return []
210+
stack = [root]
211+
result = []
212+
while stack:
213+
node = stack.pop()
214+
# 中结点先处理
215+
result.append(node.val)
216+
# 左孩子先入栈
217+
if node.left:
218+
stack.append(node.left)
219+
# 右孩子后入栈
220+
if node.right:
221+
stack.append(node.right)
222+
# 将最终的数组翻转
223+
return result[::-1]
224+
```
163225

164226

165227
Go:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /