【力扣100】226.翻转二叉树

添加链接描述

# 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

思路:

  1. 对于这种左右对称或者一层一层的算法,首先想到递归
    【力扣100】226.翻转二叉树_第1张图片
  2. 首先可以先写成这样,燃火再做剪枝:因为发现不管是否只有一个单独节点,都是可以被交换的
  3. 然后python3的独特简便交换机制:a , b = b , a


非递归做法

# 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

思路:

  1. 使用队列层序遍历二叉树
  2. continue的作用是跳出本次循环,直接进入下一次循环

你可能感兴趣的:(leetcode,算法,职场和发展)