1,题目要求
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.
给定两个非空的二进制树s和t,检查树t是否具有完全相同的结构和具有子树s的节点值。 s的子树是一个树,由s中的节点和所有节点的后代组成。 树也可以被视为自己的子树。
2,题目思路
这道题,是给定两棵树s和t,判断t是否是s的子树。
还是使用了递归手法,判断两棵树是否相等:
- 如果两个节点都为空,说明二者相同;
- 如果一个为空而另一个不为空、或者二者值不同,说明这两个树不等;
- 依次对两棵树中的节点判断,即可得到结果。
其中,我们需要对树s中的每个节点都作为根节点进行递归判断才行。
3,代码实现
1,层次遍历s中所有节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if(s == nullptr)
return false;
queue<TreeNode*> q;
q.push(s);
while(q.empty() == false){
TreeNode* node = q.front();
q.pop();
if(isSame(node, t))
return true;
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
return false;
}
private:
bool isSame(TreeNode* ss, TreeNode* tt){
if(ss == nullptr && tt == nullptr)
return true;
if(ss == nullptr || tt == nullptr ||
ss->val != tt->val)
return false;
return isSame(ss->left, tt->left) && isSame(ss->right, tt->right);
}
};
2,递归遍历s中所有节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if(s == nullptr)
return false;
if(isSame(s, t)
return true;
return (isSubtree(s->left, t) || isSubtree(s->right, t);
}
private:
bool isSame(TreeNode* ss, TreeNode* tt){
if(ss == nullptr && tt == nullptr)
return true;
if(ss == nullptr || tt == nullptr ||
ss->val != tt->val)
return false;
return isSame(ss->left, tt->left) && isSame(ss->right, tt->right);
}
};