# LeetCode #226 翻转二叉树 树 递归

## LeetCode #226 翻转二叉树

### 题目描述

     4
/   \
2     7
/ \   / \
1   3 6   9


     4
/   \
7     2
/ \   / \
9   6 3   1


#### 方法一：递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
# 这里不写可能导致13行nonetype object
if root is None: return None

temp = root.left
root.left = self.invertTree(root.right)
root.right = self.invertTree(temp)

return root

• 时间复杂度：$O(N)$
• 空间复杂度：$O(N)$

#### 方法二：迭代

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
stack = [root]

while stack:
curr = stack.pop()
if curr:
curr.left, curr.right = curr.right, curr.left
stack.append(curr.left)
stack.append(curr.right)
return root

• 时间复杂度：$O(N)$
• 空间复杂度：$O(N)$

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试