226. Invert Binary Tree

题目:

Invert a binary tree.

     4
   /   
  2     7
 /    / 
1   3 6   9

to

     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.

链接: http://leetcode.com/problems/invert-binary-tree/ 

一刷

 1 class Solution(object):
 2     def invertTree(self, root):
 3         if not root:
 4             return root
 5         current = [root]
 6         next_level = []
 7         while current:
 8             for idx, node in enumerate(current):
 9                 if node.left:
10                     next_level.append(node.left)
11                 if node.right:
12                     next_level.append(node.right)
13                 node.left, node.right = node.right, node.left
14             current, next_level = next_level, []
15         return root

一开始最主要的一步交换左右忘记了,而且入next时候其实左子树和右子树的顺序无所谓。曾经想把第3,4行去掉加入循环体内,但是需要额外判断是否为空,没有必要为了唯一一种特殊情况加入额外的步骤。

原文地址:https://www.cnblogs.com/panini/p/5642234.html