剑指offer-17:树的子结构
二叉树递归
1.遍历树A中的所有非空节点R,并且从树A中以R为根节点的子树开始判断是否包含和B树一样的结构;
2.如果树B中的节点为空,表明当前分支匹配,返回true;如果树A中节点为空但树B中的节点不为空或者树A和树B中对应的节点数值不相同,表明不匹配,返回false;最后递归判断左右子树是否匹配即可。
如果树A有m个节点,树B有n个节点,时间复杂度为O(mn)。
需要注意的是,形如
8
/ \
8 7
/ \
9 2
/ \
4 7
结构的二叉树,对应的层序遍历(链表形式)为:
[ 8, 8, 7, 9, 2, null, null, null, null, 4, 7, null, null, null, null ]
具体代码如下:
class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(!pRoot1 || !pRoot2) return false;
if(isPart(pRoot1, pRoot2)) return true;
return isPart(pRoot1->left, pRoot2) || isPart(pRoot1->right, pRoot2);
}
bool isPart(TreeNode* p1, TreeNode* p2){
if(!p2) return true;
if(!p1 || p1->val != p2->val) return false;
return isPart(p1->left, p2->left) && isPart(p1->right, p2->right);
}
};