当前位置: 首页 > news >正文

闯关leetcode——100. Same Tree

大纲

  • 题目
    • 地址
    • 内容
  • 解题
    • 代码地址

题目

地址

https://leetcode.com/problems/same-tree/description/

内容

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

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

Example 1:

Input: p = [1,2,3], q = [1,2,3]
Output: true
在这里插入图片描述

Example 2:

Input: p = [1,2], q = [1,null,2]
Output: false
在这里插入图片描述

Example 3:

Input: p = [1,2,1], q = [1,1,2]
Output: false
在这里插入图片描述

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -104 <= Node.val <= 104

解题

这题就是要比较两个二叉树中节点数值以及结构是否一致。需要注意的是,不能通过判断两个节点的数值一致而返回true,而是要更多考虑不一致的情况,比如左右节点结构是否一致以及数值是否一致。能够完全确认两个节点相同的就是它们都是nullptr,即都遍历到最后一级,且之前都没遇到返回false的情况。

#include <vector>
using namespace std;struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode() : val(0), left(nullptr), right(nullptr) {}TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};class Solution {
public:bool isSameTree(TreeNode* p, TreeNode* q) {if (p == nullptr && q == nullptr) return true;if (p == nullptr || q == nullptr) return false;if (p->val != q->val) return false;return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);}
};

在这里插入图片描述

代码地址

https://github.com/f304646673/leetcode/tree/main/100-Same-Tree


http://www.mrgr.cn/news/50032.html

相关文章:

  • 2024 年主流 10 大 CRM 系统盘点
  • 33条必看问题!腾讯云认证考试须知!
  • Jmeter 获取用户数据-全部登录
  • 电脑上怎么录制高清流畅视频?录制游戏的时候很卡怎么办?
  • 从“制造”到“智造”:中图光学测量仪器的进阶与应用
  • postgresql进行几何抽稀(DP抽稀)
  • 进程地址空间
  • 自动化检查网页的TDK,python+selenium自动化测试web的网页源代码中的title,Description,Keywords
  • 电子行业技术网站
  • 【2022统考真题】计算时间复杂度
  • Spring集成Redisson及存取几种基本类型数据
  • 已解决:“发生生成错误,是否继续并运行上次的成功的生成?”无法启动程序,系统找不到指定的文件
  • 代码随想录算法训练营Day07 | 454.四数相加II、383. 赎金信 、15. 三数之和 、18. 四数之和
  • ppt在线生成工具有哪些?6个好用的做ppt软件盘点!
  • crossover怎么运行exe文件,crossover如何安装Windows软件?crossover安装的软件无法打开怎么办
  • 从0到1打造我们专属的推荐系统
  • 推挽电路(图腾柱)
  • LeetCode Hot100 | Day4 | 层序遍历有序数组转搜索树验证搜索树搜索树中第K小的元素
  • ZFX山海证券的多元化产品策略
  • uniapp+veu3在vite.config.ts配置代理解决跨域问题