Leetcode 笔记 100 - Same Tree

题目链接:Same Tree | LeetCode OJ

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

Tags: Depth-first Search

分析

很基本的一道深度优先遍历的题,没有太多好解释的,唯一需要注意的是leetcode约定的对结点为空的两个约定:

  • left, right指向None表示没有叶子结点
  • root不为None时(即结点存在),root.val不为None

示例

class Solution:
    # @param p, a tree node
    # @param q, a tree node
    # @return a boolean
    def isSameTree(self, p, q):
      if p is None and q is None:
        return True
      if p is None or q is None or p.val != q.val:
        return False
      return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Leetcode 笔记系列的Python代码共享在https://github.com/wizcabbit/leetcode.solution

优化/简化

题目很简单,优化和简化都不会构成数量级上的影响,计算的时空复杂度都是确定的。

posted @   前端兔子喵  阅读(281)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示