bonfy / algorithm-in-5-minutes

Algorithm in 5 minutes
0 stars 0 forks source link

5. Invert Binary Tree #5

Open bonfy opened 5 years ago

bonfy commented 5 years ago

Invert a binary tree.

Example:

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 fuck off.

Leetcode: 226. Invert Binary Tree - https://leetcode.com/problems/invert-binary-tree/

bonfy commented 5 years ago

解法一: 递归 Recursive

时间复杂度 O(n), n 为 tree 的 node 数

# 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:
        if root:
            root.left, root.right = root.right, root.left
            self.invertTree(root.left)
            self.invertTree(root.right)
        return root