LeetCode:226. Invert Binary Tree

题目描述

Invert a binary tree.

Example:

Input:

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

Output:

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

本题就是让我们反转一下二叉树,左右子树进行对调。可以使用一个递归实现。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root == None:
return root
tmp = root.left
root.left = root.right
root.right = tmp
if root.left:
self.invertTree(root.left)
if root.right:
self.invertTree(root.right)
return root