AcWing 37. 树的子结构
原题链接
中等
作者:
你也叫依古比古吗
,
2020-08-30 21:11:09
,
所有人可见
,
阅读 645
C++ 代码
/**
* 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 hasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
string s1 = "";
string s2 = "";
dfs(pRoot1,s1);
dfs(pRoot2,s2);
if(s1.size() == 0 && s2.size() == 0)
return true;
if(s1.size() == 0 || s2.size() == 0)
return false;
return !(s1.find(s2) == s1.npos);
}
void dfs(TreeNode *p,string &str)
{
if(!p)
return;
str += to_string(p->val);
dfs(p -> left,str);
dfs(p -> right,str);
}
};