17.树的子结构——剑指offer
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
4 class Solution { 5 public: 6 bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) 7 { 8 if(pRoot2 == NULL || pRoot1 == NULL )//为空直接返回 9 return false; 10 return isSubtree(pRoot1, pRoot2)|| HasSubtree(pRoot1->left,pRoot2) || HasSubtree(pRoot1->right,pRoot2);//依次以根节点左右节点遍历 11 } 12 13 bool isSubtree(TreeNode* pRoot1 , TreeNode* pRoot2){ 14 if(pRoot2 == NULL) 15 return true; 16 if(pRoot1 == NULL) 17 return false; 18 return pRoot1->val == pRoot2->val && isSubtree(pRoot1->left,pRoot2->left) && isSubtree(pRoot1->right,pRoot2->right); 19 } 20 };