Subtree of Another Tree问题及解法
来源:互联网 发布:js动态修改style属性 编辑:程序博客网 时间:2024/06/05 14:25
问题描述:
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.
示例:
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.
Given tree s:
3 / \ 4 5 / \ 1 2 / 0Given tree t:
4 / \ 1 2Return false.
问题分析:
该问题与之前的两棵树是否相同的题目原理一样,我在此处采用了BFS,利用队列求解。
过程详见代码:
/** * 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 isSubtree(TreeNode* s, TreeNode* t) { if(s == NULL && t != NULL) return false; queue<TreeNode* > sq; queue<TreeNode* > tq; TreeNode* tt = t; TreeNode* ss = s; if(s->val == t->val) { if(t->left != NULL) tq.push(t->left); if(t->right != NULL)tq.push(t->right); if(s->left != NULL)sq.push(s->left); if(s->right != NULL)sq.push(s->right); while(!tq.empty() && !sq.empty()) { t = tq.front(); s = sq.front(); tq.pop(); sq.pop(); if(s->val == t->val) { if(t->left != NULL) tq.push(t->left); if(t->right != NULL)tq.push(t->right); if(s->left != NULL)sq.push(s->left); if(s->right != NULL)sq.push(s->right);}else return isSubtree(ss->left,tt) || isSubtree(ss->right,tt);}return tq.empty() && sq.empty() || isSubtree(ss->left,tt) || isSubtree(ss->right,tt);} return isSubtree(ss->left,tt) || isSubtree(ss->right,tt); }};
0 0
- Subtree of Another Tree问题及解法
- Subtree of Another Tree
- Subtree of Another Tree
- leetcode[Subtree of Another Tree]//待整理多种解法
- 572. Subtree of Another Tree
- LeetCode: Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- leetcode572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- leetcode : subtree of another tree
- 572. Subtree of Another Tree
- 在Linux 系统内存分配
- SQL Server 的所有表查询和注释说明查询
- 深度学习之风格迁移(二)——Fast Neural Style(Johnson)
- spring 事务
- xilinx 浮点数IP核的用法- 浮点数除法
- Subtree of Another Tree问题及解法
- [ElasticSearch2.x]Queries vs Filters
- mysql 使用inet_aton和inet_ntoa处理ip地址数据
- POI导出excel表时,常用到的方法
- [DP]413. Arithmetic Slices
- [Java面试九]脚本语言知识总结.
- lamp安装记录
- 滑动窗口算法
- Class.forName(xxx.xx.xx) 的作用