代码随想录打卡(14) —— 二叉树层序遍历

力扣102. 二叉树的层序遍历

递归方法的回溯问题要留意一下。

# 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]]:
        res = []
        layth = 0  # 层数标记
        def traversal(root:TreeNode,layth):
            if root == None:
                return 
            if len(res) == layth: # 判断是第几层,如果已经层数+1了,那么创建新层
                res.append([])
            res[layth].append(root.val)
            if root.left:
                traversal(root.left,layth + 1) # 回溯到这执行下一步时
            if root.right:  # 执行这一步layth会-1由于上一层递归时+1
                traversal(root.right,layth + 1)
            
            return res
        
        traversal(root,layth)
        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 None
        root.left, root.right = root.right, root.left # # 前序遍历
        self.invertTree(root.left) #左
        self.invertTree(root.right) #右
        return root

力扣101.对称二叉树

只能后序

# 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:
        if not root:
            return True
        return self.compare(root.left, root.right)
        
    def compare(self, left, right):
        #首先排除空节点的情况
        if left == None and right != None: 
            return False
        elif left != None and right == None: 
            return False
        elif left == None and right == None: 
            return True
        #排除了空节点,再排除数值不相同的情况
        elif left.val != right.val: 
            return False
        
        #此时就是:左右节点都不为空,且数值相同的情况
        #此时才做递归,做下一层的判断
        outside = self.compare(left.left, right.right) #左子树:左、 右子树:右
        inside = self.compare(left.right, right.left) #左子树:右、 右子树:左
        isSame = outside and inside #左子树:中、 右子树:中 (逻辑处理)
        return isSame

你可能感兴趣的:(算法,数据结构)