[关闭]
@Lin-- 2020-02-17T12:13:20.000000Z 字数 546 阅读 376

invertTree

Leetcode


翻转左右子树:只需要将左子树指针指向右指针,有指针指向左指针,不断递归,直到叶子结点。

  1. '''
  2. # File: invertTree.py
  3. # Author: 0HP
  4. # Date: 20200217
  5. # Purpose: solve the problem in website:
  6. https://leetcode.com/problems/invert-binary-tree/
  7. '''
  8. # Definition for a binary tree node.
  9. class TreeNode:
  10. def __init__(self, x):
  11. self.val = x
  12. self.left = None
  13. self.right = None
  14. class Solution:
  15. def invertTree(self, root: TreeNode) -> TreeNode:
  16. if root==None:
  17. return None
  18. root.left,root.right=root.right,root.left
  19. if not root.left==None:
  20. root.left=self.invertTree(root.left)
  21. if not root.right==None:
  22. root.right=self.invertTree(root.right)
  23. return root
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注