Invert a binary tree#

Levels: level-0
Data structures: tree

LeetCode

Description#

  • Invert a binary tree

Example#

 1Input:
 2     4
 3   /   \
 4  2     7
 5 / \   / \
 61   3 6   9
 7
 8Output:
 9     4
10   /   \
11  7     2
12 / \   / \
139   6 3   1

Python Solution#

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