LeetCode C++ 100. Same Tree【Tree/DFS/BFS】简单
发布日期:2021-07-01 02:49:58
浏览次数:2
分类:技术文章
本文共 1725 字,大约阅读时间需要 5 分钟。
Given two binary trees, 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: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3]Output: true
Example 2:
Input: 1 1 / \ 2 2 [1,2], [1,null,2]Output: false
Example 3:
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2]Output: false
题意:给定两个二叉树,编写一个函数来检验它们是否相同。如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
思路1:DFS。很简单的递归函数。
代码如下:
class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if (p == nullptr && q) return false; if (q == nullptr && p) return false; if (p == nullptr && q == nullptr) return true; if (p->val == q->val) return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); else return false; }};
思路2:BFS,用一个队列同时存储两棵树上对应的结点。这里需要存储空结点 nullptr
,原因是要保持两棵树之间结构的对应。然后每次弹出两棵树的对应结点,如果都为空,就跳过;否则如果存在且值相等,就继续同时存储两棵树上面相同位置的指针;如果一个存在而另一个不存在,或者值不同,就直接返回 false
。
代码如下:
class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { queuequ; qu.push(p); qu.push(q); while (!qu.empty()) { p = qu.front(); qu.pop(); q = qu.front(); qu.pop(); if (!p && !q) continue; // 都为空, 则跳过后面的比较 if (!p || !q) return false; if (p->val != q->val) return false; qu.push(p->left); // 同时存储两棵树上面相同位置的指针 qu.push(q->left); qu.push(p->right); qu.push(q->right); } return true; }};
转载地址:https://memcpy0.blog.csdn.net/article/details/108138963 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
感谢大佬
[***.8.128.20]2024年05月04日 00时42分44秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
linux下安装jenkins+git+python
2019-05-01
解决uiautomatorviewer中添加xpath的方法
2019-05-01
性能测试的必要性评估以及评估方法
2019-05-01
Spark学习——利用Mleap部署spark pipeline模型
2019-05-01
Oracle创建表,修改表(添加列、修改列、删除列、修改表的名称以及修改列名)
2019-05-01
使用redis实现订阅功能
2019-05-01
对称加密整个过程
2019-05-01
java内存模型
2019-05-01
volatile关键字
2019-05-01
tomcat_关闭
2019-05-01
Servlet_快速入门
2019-05-01
Servlet_生命周期方法
2019-05-01
Servlet_体系结构
2019-05-01
Servlet_urlpartten配置
2019-05-01
Request_原理
2019-05-01
Request_继承体系
2019-05-01
前端权限控制:获取用户信息接口构造数据
2019-05-01
有状态服务和无状态服务
2019-05-01
七牛云存储:断点续传
2019-05-01