题目:
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 2Return 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 isSubtree(TreeNode* s, TreeNode* t) {
vector<TreeNode*> nodes;
preorder(s, nodes);
for (auto n : nodes) {
if (sameTree(t, n)) {
return true;
}
}
return false;
}
private:
void preorder(TreeNode *s, vector<TreeNode*> &nodes) {
if (s == NULL) {
return;
}
nodes.push_back(s);
preorder(s->left, nodes);
preorder(s->right, nodes);
}
bool sameTree(TreeNode *t1, TreeNode *t2) {
if (t1 == NULL && t2 == NULL) {
return true;
}
else if (t1 == NULL || t2 == NULL) {
return false;
}
else {
if (t1->val != t2->val) {
return false;
}
else {
return sameTree(t1->left, t2->left) && sameTree(t1->right, t2->right);
}
}
}
};