输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; bool doestree1hastree2(TreeNode* pRoot1, TreeNode* pRoot2) { if (pRoot2 == NULL) return true; if (pRoot1 == NULL) return false; if (pRoot1->val != pRoot2->val) return false; //当头结点一样的时候,再判断树1和树2左子树和右子树是否都相等。只有都相等时,才返回真,否则返回假 return doestree1hastree2(pRoot1->left, pRoot2->left) && doestree1hastree2(pRoot1->right, pRoot2->right); } bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { bool res = false; if (pRoot1 != NULL&&pRoot2 != NULL) { if (pRoot1->val == pRoot2->val)//若有相同的结点,继续判断是否2在1中 res = doestree1hastree2(pRoot1, pRoot2); if (!res) { res=HasSubtree(pRoot1->left, pRoot2); } if (!res)//若左子树中没有找到和树2一致的子树,则在右子树中找 { res = HasSubtree(pRoot1->right, pRoot2); } } return res; }
刷题--树的子结构
最新推荐文章于 2022-04-07 14:51:04 发布