Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
思路:立马想到递归,出口立马想到是root为NULL。问题就在与循环体上,既然是反转左右树,那么以任意节点为例,只需要将其左树的值转为右树的值,右树的值转为左树的值即可。循环体该返回什么呢?例如此时在节点2上,我们执行完循环体,2节点的左右树已经互换了,而2节点需要上一级节点将其与7进行互换所以返回其自身,等待与7的互换即可。
python知识:多变量在同一语句上进行赋值:a,b=b,a完成a与b的值的互换。
代码:
class Solution:
def invertTree(self, root):
if not root:return
tmp=root.left
root.left=self.invertTree(root.right)
root.right=self.invertTree(tmp)
return root
简化循环体:
class Solution:
def invertTree(self, root):
if not root:return
root.left,root.right=self.invertTree(root.right),self.invertTree(root.left)
return root