【Leetcode】代码随想录Day15|二叉树2.0

文章目录

    • 层序遍历
      • [102 二叉树的层序遍历](#102 二叉树的层序遍历)
    • [226 翻转二叉树](#226 翻转二叉树)
    • [101 对称二叉树](#101 对称二叉树)

层序遍历

队列先进先出,符合一层一层遍历的逻辑,而用栈先进后出适合模拟深度优先遍历也就是递归的逻辑。

102 二叉树的层序遍历

递归法

python 复制代码
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        levels = []
        self.helper(root, 0, levels)
        return levels
    
    def helper(self, node, level, levels):
        if not node:
            return
        if len(levels) == level:
            levels.append([])
        levels[level].append(node.val)
        self.helper(node.left, level + 1, levels)
        self.helper(node.right, level + 1, levels)

利用长度和队列(迭代)

python 复制代码
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        queue = collections.deque([root])
        result = []
        while queue:
            level = []
            for _ in range(len(queue)):
                cur = queue.popleft()
                level.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            result.append(level)
        return result

226 翻转二叉树

初始思路

使用递归。先处理root,如果是None,则return None。接着将反转的root.left赋给root.right,另一边也一样。

python 复制代码
class Solution(object):
    def invertTree(self, root):
        if not root:
            return None

        tmp = root.left
        root.left = self.invertTree(root.right)
        root.right = self.invertTree(tmp)
        return root

:这是递归法的前序遍历,其余遍历方法和迭代法需要之后补充

101 对称二叉树

初始思路

root.left和root.right两个子树在一方反转后是否相等。但空间复杂度不太妙,还需要多traverse一次,应该直接在traverse中查看是否对称。

python 复制代码
class Solution(object):
    def invertTree(self, root):
        if not root:
            return None
        
        tmp = root.left
        root.left = self.invertTree(root.right)
        root.right = self.invertTree(tmp)
        return root

    def compare(self, left, right):
        if not left and not right:
            return True
        if not left or not right:
            return False
        if left.val == right.val:
            return self.compare(left.left, right.left) and self.compare(left.right, right.right)
        return False

    def isSymmetric(self, root):
        # invert tree and see if it is the same as itself
        if not root:
            return True

        invert_left = self.invertTree(root.left)
        return self.compare(invert_left, root.right)

代码随想录

python 复制代码
class Solution:
    def isSymmetric(self, root: 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

:这是递归法的前序遍历,其余遍历方法和迭代法需要之后补充

相关推荐
敲上瘾3 分钟前
子数组问题——动态规划
java·c++·算法·动态规划
eason_fan10 分钟前
前端手撕代码(bigo)
算法·面试
Hello kele11 分钟前
大型项目,选择conda还是Poetry要点分析
人工智能·python·conda·ai编程·poetry
SmallBambooCode14 分钟前
【人工智能】【Python】在Scikit-Learn中使用KNN(K最近邻算法)
人工智能·python·机器学习·scikit-learn·近邻算法
jaffe—fly17 分钟前
【解决问题】conda 虚拟环境内,`pip list` 展示全局的包
python·conda·pip
带上一无所知的我17 分钟前
解锁Conda:Python环境与包管理的终极指南
开发语言·python·conda
changwan22 分钟前
基于Celery+Supervisord的异步任务管理方案
后端·python·性能优化
君秋水22 分钟前
Python异步编程指南:asyncio从入门到精通(Python 3.10+)
后端·python
302wanger23 分钟前
ARTS-算法-长度最小的子数组
算法
君秋水35 分钟前
FastAPI教程:20个核心概念从入门到 happy使用
后端·python·程序员