Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
相关一个有趣的故事是Max去google面试,因为没有写出这道题被拒了……
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.
算法很简单,对于每个树的左右树交换位置,之后递归调用就可以了
python代码
def inv(ro):
if (ro is None):return(None)
if (ro.left or ro.right):
ro.left=inv(ro.left)
ro.right=inv(ro.right)
ro.left,ro.right = ro.right,ro.left
return(ro)
else:
return(ro)