Invert Binary Tree

太过爱你忘了你带给我的痛 2021-12-17 10:41 325阅读 0赞

Invert a binary tree.

  1. 4
  2. / \
  3. 2 7
  4. / \ / \
  5. 1 3 6 9

to

  1. 4
  2. / \
  3. 7 2
  4. / \ / \
  5. 9 6 3 1

反转二叉树,其实就是自顶向下递归翻转.代码如下:

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def invertTree(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: TreeNode
  12. """
  13. if root:
  14. root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
  15. return root

转载于:https://www.cnblogs.com/sherylwang/p/5661244.html

发表评论

表情:
评论列表 (有 0 条评论,325人围观)

还没有评论,来说两句吧...

相关阅读