mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 15:09:40 +08:00
Update 二叉树的迭代遍历.md
This commit is contained in:
@ -240,14 +240,14 @@ class Solution {
|
||||
# 前序遍历-迭代-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:
|
||||
@ -264,19 +264,19 @@ class Solution:
|
||||
def inorderTraversal(self, root: TreeNode) -> List[int]:
|
||||
if not root:
|
||||
return []
|
||||
stack = [] # 不能提前将root结点加入stack中
|
||||
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
|
||||
```
|
||||
@ -291,7 +291,7 @@ class Solution:
|
||||
result = []
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
# 中结点先处理
|
||||
# 中节点先处理
|
||||
result.append(node.val)
|
||||
# 左孩子先入栈
|
||||
if node.left:
|
||||
@ -304,7 +304,7 @@ class Solution:
|
||||
```
|
||||
|
||||
#### Python 后序遍历的迭代新解法:
|
||||
* 本解法不同于前文介绍的`逆转前序遍历调整后的结果`,而是采用了对每个结点直接处理。
|
||||
* 本解法不同于前文介绍的`逆转前序遍历调整后的结果`,而是采用了对每个节点直接处理。
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
@ -315,7 +315,7 @@ class Solution:
|
||||
current = root
|
||||
|
||||
while current or stack:
|
||||
if current: # 一次处理完一个结点和他的左右儿子结点,不处理孙子结点,孙子结点由左右儿子等会分别处理。
|
||||
if current: # 一次处理完一个节点和他的左右儿子节点,不处理孙子节点,孙子节点由左右儿子等会分别处理。
|
||||
stack.append(current) # 入栈自己
|
||||
|
||||
if current.right:
|
||||
@ -329,7 +329,7 @@ class Solution:
|
||||
|
||||
node = stack.pop() # A处,出的是左儿子,如果无左儿子,出的就是右儿子,如果连右儿子也没有,出的就是自己了。
|
||||
|
||||
# 如果 node 是叶子结点,就可以收割了;如果左右儿子都已经被收割了,也可以收割
|
||||
# 如果 node 是叶子节点,就可以收割了;如果左右儿子都已经被收割了,也可以收割
|
||||
if (node.left is None or node.left in popped_nodes) and \
|
||||
(node.right is None or node.right in popped_nodes):
|
||||
popped_nodes.add(node)
|
||||
|
Reference in New Issue
Block a user