当前位置:网站首页>[LeetCode]100. 相同的树
[LeetCode]100. 相同的树
2022-06-27 19:35:00 【阿飞算法】
题目
100. 相同的树
给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 1:
输入:p = [1,2,3], q = [1,2,3]
输出:true
示例 2:
输入:p = [1,2], q = [1,null,2]
输出:false
示例 3:
输入:p = [1,2,1], q = [1,1,2]
输出:false
提示:
两棵树上的节点数目都在范围 [0, 100] 内
-104 <= Node.val <= 104
方法1:DFS
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
方法2:BFS
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
Queue<TreeNode> queue1 = new LinkedList<>();
Queue<TreeNode> queue2 = new LinkedList<>();
queue1.offer(p);
queue2.offer(q);
while (!queue1.isEmpty()) {
TreeNode currP = queue1.poll();
TreeNode currQ = queue2.poll();
if (currP == null && currQ == null) continue;
if (currP.val != currQ.val) return false;
TreeNode currPLeft = currP.left;
TreeNode currPRight = currP.right;
TreeNode currQLeft = currQ.left;
TreeNode currQRight = currQ.right;
if (currPLeft == null ^ currQLeft == null) return false;
if (currPRight == null ^ currQRight == null) return false;
if (currPLeft != null) queue1.offer(currPLeft);
if (currPRight != null) queue1.offer(currPRight);
if (currQLeft != null) queue2.offer(currQLeft);
if (currQRight != null) queue2.offer(currQRight);
}
return true;
}
边栏推荐
猜你喜欢

After being forced to develop the app within 20 days, the group was laid off, and the technical director angrily criticized it: I wish "closure as soon as possible!"

DO280OpenShift访问控制--security policy和章节实验

Burp suite遇到的常见问题

空指针异常

AI painting minimalist tutorial

CORBA 架构体系指南(通用对象请求代理体系架构)

Go from entry to practice - dependency management (notes)

C语言程序设计详细版 (学习笔记1) 看完不懂,我也没办法。

Go从入门到实战——仅执行一次(笔记)

100 important knowledge points that SQL must master: filtering data
随机推荐
我想我要开始写我自己的博客了。
Go from introduction to actual combat - all tasks completed (notes)
SQL必需掌握的100个重要知识点:创建计算字段
Go從入門到實戰——接口(筆記)
JVM memory structure when creating objects
Galaxy Kirin system LAN file sharing tutorial
matlab查找某一行或者某一列在矩阵中的位置
SQL必需掌握的100个重要知识点:IN 操作符
猜拳游戏专题训练
Little known MySQL import data
数组作业题
Knowledge sorting of exception handling
STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP
Codeforces Round #721 (Div. 2)
Go从入门到实战——仅需任意任务完成(笔记)
Go从入门到实战——行为的定义和实现(笔记)
流程控制任务
Let Ma Huateng down! Web3.0, hopeless
Kirin V10 installation font
快速excel导出