LeetCode 226. Invert Binary Tree

题目

Invert a binary tree.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Input:


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

Output:

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

Trivia:

This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.

思路

Recursive or Iterative.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root