Topic:
Invert a binary tree.
4 / 2 7/\ /1 3 6 9
To
4 / 7 2/\ /9 6 3 1
Trivia:
This problem is inspired by this original tweets by Max Howell:
google:90% of our engineers with the software you wrote (Homebrew), but can ' t invert a binary tree on a Whitebo ard so fuck off.
Links: http://leetcode.com/problems/invert-binary-tree/
A brush
1 classsolution (object):2 defInverttree (self, root):3 if notRoot:4 returnRoot5Current =[Root]6Next_level = []7 whileCurrent :8 forIDX, nodeinchEnumerate (current):9 ifNode.left:Ten next_level.append (node.left) One ifNode.right: A next_level.append (node.right) -Node.left, node.right =Node.right, Node.left -Current, Next_level =Next_level, [] the returnRoot
At the beginning the main step of the exchange left and right forgotten, and in the next time in fact, the order of Saozi is irrelevant. Once wanted to remove the 3rd, 4 lines into the loop body, but need additional judgment is empty, there is no need for the only special case to add additional steps.
226. Invert Binary Tree