python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return root
root.left,root.right=self.invertTree(root.right),self.invertTree(root.left)
return root
思路:
- 对于这种左右对称或者一层一层的算法,首先想到递归
- 首先可以先写成这样,燃火再做剪枝:因为发现不管是否只有一个单独节点,都是可以被交换的
- 然后python3的独特简便交换机制:
a , b = b , a
非递归做法
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
q=collections.deque()
q.append(root)
while q:
cur=q.popleft()
if not cur:
continue
cur.left,cur.right=cur.right,cur.left
q.append(cur.left)
q.append(cur.right)
return root
思路:
- 使用队列层序遍历二叉树
- continue的作用是跳出本次循环,直接进入下一次循环