LeetCode刷题 | 572. Subtree of Another Tree
来源:互联网 发布:js display none 显示 编辑:程序博客网 时间:2024/06/06 13:16
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3 / \ 4 5 / \ 1 2Given tree t:
4 / \ 1 2Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3 / \ 4 5 / \ 1 2 / 0Given tree t:
4 / \ 1 2
Return false
解题思路:
这题要求给定两棵树s和t,如果t是s的子树那么返回true否则返回false,我的思路是这样,使用广度优先遍历s的每一个点,如果发现s中某个节点a的值和t的根节点的值相同,那么检测以a为根节点的子树和树t是否完全相同,如果完全相同则返回true,否者继续广度遍历s
广度遍历s使用头文件include<queue>实现,检测以a为根节点子树和t是否完全相同使用的是深度优先遍历
class Solution {
#include<queue>
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
queue<TreeNode *> Q;
Q.push(s);
while(!Q.empty())
{
TreeNode * o=Q.front(); Q.pop();
if(o==NULL) continue;
Q.push(o->left);Q.push(o->right);
if(o->val==t->val) if(p(o,t))return true;
}
return false;
}
bool p(TreeNode *s,TreeNode * t)
{
if(s==NULL&&t==NULL) returntrue;
else if(s==NULL||t==NULL) return false;
if(s->val!=t->val) return false;
else
{
if(p(s->left,t->left)&&p(s->right,t->right))
return true;
else return false;
}
}
};
这题还有一个更好的方法就是只比较s中最大深度与t相同的子树与t,比较他们是否相同,这样效率能提升很多倍- LeetCode刷题 | 572. Subtree of Another Tree
- [LeetCode]572. Subtree of Another Tree
- [leetcode]: 572. Subtree of Another Tree
- leetcode 572. Subtree of Another Tree
- [leetcode: Python]572. Subtree of Another Tree
- [leetcode]572. Subtree of Another Tree
- LeetCode 572. Subtree of Another Tree
- [LeetCode] 572. Subtree of Another Tree
- LeetCode-572. Subtree of Another Tree (Java)
- Leetcode-572. Subtree of Another Tree
- leetcode 572. Subtree of Another Tree
- LeetCode 572. Subtree of Another Tree
- [LeetCode]572. Subtree of Another Tree
- 【LeetCode】572. Subtree of Another Tree
- leetcode 572. Subtree of Another Tree
- leetcode#572. Subtree of Another Tree
- LeetCode 572. Subtree of Another Tree
- LeetCode: Subtree of Another Tree
- Wifi网络判断
- python3之1002.写出这个数(20分)
- mac下将根目录/更改组到普通用户,导致sudo不能用
- 什么是面向对象?附带面向对象选项卡
- 邮箱,手机号,身份证的正则表达式
- LeetCode刷题 | 572. Subtree of Another Tree
- MVC简介
- 完美解决glide+StaggeredGridLayoutManager 图片加载大小不正常的问题
- 2017-12-10杭电OJ2016 《数据的交换输出》
- matlab与stm32之间利用串口通信记录
- ubuntu Please resume and shutdown Windows fully (no hibernation or fast restarting) disk problem+
- 51Nod 1279 扔盘子 栈模拟
- 使用MVP实现功能
- 使用jquery实现计算两个日期差