Update 0226.翻转二叉树.md

This commit is contained in:
Baturu
2021-06-04 01:45:10 -07:00
committed by GitHub
parent 2a7c3cb87c
commit b69ca00d2f

View File

@ -230,6 +230,56 @@ class Solution {
Python Python
> 递归法:前序遍历
```python
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
root.left, root.right = root.right, root.left #中
self.invertTree(root.left) #左
self.invertTree(root.right) #右
return root
```
> 迭代法:深度优先遍历(前序遍历)
```python
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
st = []
st.append(root)
while st:
node = st.pop()
node.left, node.right = node.right, node.left #中
if node.right:
st.append(node.right) #右
if node.left:
st.append(node.left) #左
return root
```
> 迭代法:广度优先遍历(层序遍历)
```python
import collections
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
queue = collections.deque() #使用deque()
if root:
queue.append(root)
while queue:
size = len(queue)
for i in range(size):
node = queue.popleft()
node.left, node.right = node.right, node.left #节点处理
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root
```
Go Go
```Go ```Go
func invertTree(root *TreeNode) *TreeNode { func invertTree(root *TreeNode) *TreeNode {