Update 二叉树的迭代遍历.md

This commit is contained in:
Lane Zhang (张健)
2024-10-23 10:33:48 +08:00
committed by GitHub
parent a36358e068
commit bf540436f2

View File

@ -240,14 +240,14 @@ class Solution {
# 前序遍历-迭代-LC144_二叉树的前序遍历 # 前序遍历-迭代-LC144_二叉树的前序遍历
class Solution: class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]: def preorderTraversal(self, root: TreeNode) -> List[int]:
# 根点为空则返回空列表 # 根点为空则返回空列表
if not root: if not root:
return [] return []
stack = [root] stack = [root]
result = [] result = []
while stack: while stack:
node = stack.pop() node = stack.pop()
# 中点先处理 # 中点先处理
result.append(node.val) result.append(node.val)
# 右孩子先入栈 # 右孩子先入栈
if node.right: if node.right:
@ -264,19 +264,19 @@ class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]: def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root: if not root:
return [] return []
stack = [] # 不能提前将root点加入stack中 stack = [] # 不能提前将root点加入stack中
result = [] result = []
cur = root cur = root
while cur or stack: while cur or stack:
# 先迭代访问最底层的左子树 # 先迭代访问最底层的左子树
if cur: if cur:
stack.append(cur) stack.append(cur)
cur = cur.left cur = cur.left
# 到达最左点后处理栈顶 # 到达最左点后处理栈顶
else: else:
cur = stack.pop() cur = stack.pop()
result.append(cur.val) result.append(cur.val)
# 取栈顶元素右 # 取栈顶元素右
cur = cur.right cur = cur.right
return result return result
``` ```
@ -291,7 +291,7 @@ class Solution:
result = [] result = []
while stack: while stack:
node = stack.pop() node = stack.pop()
# 中点先处理 # 中点先处理
result.append(node.val) result.append(node.val)
# 左孩子先入栈 # 左孩子先入栈
if node.left: if node.left:
@ -304,7 +304,7 @@ class Solution:
``` ```
#### Python 后序遍历的迭代新解法: #### Python 后序遍历的迭代新解法:
* 本解法不同于前文介绍的`逆转前序遍历调整后的结果`,而是采用了对每个点直接处理。 * 本解法不同于前文介绍的`逆转前序遍历调整后的结果`,而是采用了对每个点直接处理。
```python ```python
class Solution: class Solution:
@ -315,7 +315,7 @@ class Solution:
current = root current = root
while current or stack: while current or stack:
if current: # 一次处理完一个点和他的左右儿子点,不处理孙子点,孙子点由左右儿子等会分别处理。 if current: # 一次处理完一个点和他的左右儿子点,不处理孙子点,孙子点由左右儿子等会分别处理。
stack.append(current) # 入栈自己 stack.append(current) # 入栈自己
if current.right: if current.right:
@ -329,7 +329,7 @@ class Solution:
node = stack.pop() # A处出的是左儿子如果无左儿子出的就是右儿子如果连右儿子也没有出的就是自己了。 node = stack.pop() # A处出的是左儿子如果无左儿子出的就是右儿子如果连右儿子也没有出的就是自己了。
# 如果 node 是叶子点,就可以收割了;如果左右儿子都已经被收割了,也可以收割 # 如果 node 是叶子点,就可以收割了;如果左右儿子都已经被收割了,也可以收割
if (node.left is None or node.left in popped_nodes) and \ if (node.left is None or node.left in popped_nodes) and \
(node.right is None or node.right in popped_nodes): (node.right is None or node.right in popped_nodes):
popped_nodes.add(node) popped_nodes.add(node)