更优雅更简单更优的解法

树的子结构

http://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88

只需将两个树前序遍历,然后判断是否为字串
class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{ if(pRoot2==NULL) return false;
string s1;
pre(pRoot1,s1);
string s2;
pre(pRoot2, s2);
if (s1.find(s2) == string::npos) return false;
return true;
}
void pre(TreeNode * root,string& s)
{
if (root == NULL) return;
s += '0' + root->val;
pre(root->left, s);
pre(root->right, s);
return;
}
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-18 18:30
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务