Skip to content

Commit

Permalink
Update 二叉树的统一迭代法.md
Browse files Browse the repository at this point in the history
  • Loading branch information
z80160280 committed Jun 2, 2021
1 parent 9707fbc commit 2a7c3cb
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions problems/二叉树的统一迭代法.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,78 @@ Java:

```
Python
> 迭代法前序遍历

```python
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
result = []
st= []
if root:
st.append(root)
while st:
node = st.pop()
if node != None:
if node.right: #右
st.append(node.right)
if node.left: #左
st.append(node.left)
st.append(node) #中
st.append(None)
else:
node = st.pop()
result.append(node.val)
return result
```

> 迭代法中序遍历
```python
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
result = []
st = []
if root:
st.append(root)
while st:
node = st.pop()
if node != None:
if node.right: #添加右节点(空节点不入栈)
st.append(node.right)

st.append(node) #添加中节点
st.append(None) #中节点访问过,但是还没有处理,加入空节点做为标记。

if node.left: #添加左节点(空节点不入栈)
st.append(node.left)
else: #只有遇到空节点的时候,才将下一个节点放进结果集
node = st.pop() #重新取出栈中元素
result.append(node.val) #加入到结果集
return result
```

> 迭代法后序遍历
```python
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
result = []
st = []
if root:
st.append(root)
while st:
node = st.pop()
if node != None:
st.append(node) #中
st.append(None)

if node.right: #右
st.append(node.right)
if node.left: #左
st.append(node.left)
else:
node = st.pop()
result.append(node.val)
return result
```

Go:
> 前序遍历统一迭代法
Expand Down

0 comments on commit 2a7c3cb

Please sign in to comment.