It like the check pattern, but the different is here is tree. So
1. use preorder(or inorder/postorder) to traverse the tree s
2. when meet the same node val, check tree s and t
3. pattern for traverse and check:
traverse(s, t):
if(s == nullptr)
return false;
bool res = false;
if(s->val == t->val)
res |= check(s, t);
if(res == false)
res |= traverse(s->left, t) || traverse(s->right, t);
return res;
check(s, t):
if(s == null && p == null)
return true;
if(s == null || p == null)
return false;
if(s->val != t->val)
return false;
return check(s->left, t->left) && check(s->right, t->right);
本文介绍了一种用于检查一棵树是否为另一棵树的子树的算法。通过先序遍历(或中序、后序遍历),当遇到相同的节点值时,进行深入的子树匹配检查。该算法分为两部分:遍历和检查。遍历函数首先检查当前节点是否为空,然后检查当前节点的值是否与目标节点的值相等并调用检查函数,最后递归地遍历左右子树。检查函数则比较两个树的结构是否完全相同。


被折叠的 条评论
为什么被折叠?



