Title: Invert Binary Tree Source: leetcode.com
Invert a binary tree.
1 2 3 4 5 |
4 / \ 2 7 / \ / \ 1 3 6 9 |
to
1 2 3 4 5 |
4 / \ 7 2 / \ / \ 9 6 3 1 |
Trivia:
Python solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
''' https://leetcode.com/problems/invert-binary-tree/ ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root or (not root.left and not root.right): return root self.invertTree(root.left) self.invertTree(root.right) temp = root.left root.left = root.right root.right = temp return root |