25期代码随想录算法训练营第十四天 | 二叉树 | 层序遍历(10道题)、226.翻转二叉树 、101.对称二叉树 2

目录

  • 层序遍历 10
  • 226.翻转二叉树
  • 101.对称二叉树 2

层序遍历 10

链接

# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        res = []
        q = deque([root])
        
        while q:
            level = []
            for _ in range(len(q)):
                node = q.popleft()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
                level.append(node.val)
            res.append(level)
        
        return res

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

        stack = [root]

        while stack:
            node = stack.pop()
            node.left, node.right = node.right, node.left

            if node.left:
                stack.append(node.left)
            
            if node.right:
                stack.append(node.right)

        return root

101.对称二叉树 2

链接

# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def compare(left,right):
            if left == None and right != None: return False
            elif left == None and right == None: return True
            elif left != None and right == None: return False
            elif left.val != right.val: return False

            outside = compare(left.left, right.right)
            inside = compare(left.right,right.left)

            return outside and inside
        
        return compare(root.left, root.right)

你可能感兴趣的:(算法训练营二刷,算法,二叉树,leetcode,python)