leetcode-100. Same Tree · Tree + DFS + Queue
2024-09-01 14:17:22
题面
对比两棵二叉树是否相同,返回结果。
思路
1. 递归解决DFS
首先判断根节点,如果都空,返回true;
如果一空一不空,返回false;
如果都不空,判断两节点值是否相同,若不同,返回false,若相同,递归左子树、右子树
源码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == nullptr && q == nullptr)
return true;
else if(p == nullptr || q == nullptr)
return false;
else
{
if(p->val == q->val)
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
else
return false;
}
}
};
2. 层序遍历解决: 队列
1. 首先判断根节点,如果都空,返回true;
2. 如果一空一不空,返回false;
3. 如果都不空,新建队列,两节点入队。如果队列不空,出队两个元素,如果都为空,继续continue(而不是像判断头节点那样返回true),如果一空一不空,返回false;
4. 如果都不空,判断该值是否相等,若不相等,返回false; 若相等,那么分别将当前节点左孩子(2个)、右孩子(2个)入队,循环。
即:这种方法是为了在过程中返回false,最后遍历完毕,返回true.
源码
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == nullptr && q == nullptr)
return true;
else if(p == nullptr || q == nullptr)
return false;
queue<TreeNode*> tmp;
tmp.push(p); tmp.push(q);
while(!tmp.empty())
{
TreeNode *pp, *qq;
pp = tmp.front(); tmp.pop();
qq = tmp.front(); tmp.pop();
if(pp == nullptr && qq == nullptr)
continue;
else if(pp == nullptr || qq == nullptr)
return false; if(pp->val != qq->val)
return false;
else
{
tmp.push(pp->left); tmp.push(qq->left);
tmp.push(pp->right); tmp.push(qq->right);
}
}
return true;
}
};
最新文章
- BZOJ4455: [Zjoi2016]小星星
- android实现控制视频播放次数
- 修复 Firefox 下本地使用 Bootstrap 3 时 glyphicon 不显示问题
- 跟着百度学PHP[4]-OOP面对对象编程-2-属性和方法
- 几种方式实现Javaweb页面跳转
- HDU4611+数学
- Web Service和ISAPI的区别与联系 转
- C#入门经典(第五版)学习笔记(二)
- .net FrameWork4.0安装未成功
- accept: Invalid argument linux 网络编程
- Linux设置DNS地址及清理DNS缓存方法
- [LeetCode] Task Scheduler 任务行程表
- git报错:&#39;fatal:remote origin already exists
- 28自定义View 模仿联系人字母侧栏
- memcached 学习
- Django APP打包重用
- Postman测试api@RequestBody接收参数
- Xshell配置ssh免密码登录-密钥公钥(Public key)
- 深度解析Java中的那把锁
- python中括号的使用
热门文章
- 阶段5 3.微服务项目【学成在线】_day16 Spring Security Oauth2_09-SpringSecurityOauth2研究-Oauth2密码模式授权
- 解析python 命令的-u参数
- 123457123457#0#-----com.cym.shuXueWangGuo1--前拼后广--儿童数学
- 【Leetcode_easy】696. Count Binary Substrings
- Python之汉诺塔递归运算
- iOS-UITextField的使用
- WordPress简洁的SEO标题、关键词和描述
- word模板文档填充数据
- 解决电脑开机连不上网问题(Windows检测:远程计算机或设备将不接受连接)
- json 和对象互相转换