标签:要求 bool nbsp b树 return code root 相等 number
2、思路:
(1)首先确定传入的是否是空树;
(2)先判断A的根与B子树是否相等;如果不相等,则比较A的左子树是否和B子树相等;再不相等则判断A的右子树是否和B子树相等;
备注:
A树在判断函数中为空有两种情况:
a.如果A树为空且B树不为空说明不匹配,
b.如果A为空,B为空,则说明匹配。
struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; bool isSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { if (pRoot1 == NULL && pRoot2 != NULL) return false; if (pRoot2 == NULL) return true; if (pRoot1->val != pRoot2->val) return false; return isSubtree(pRoot1->left, pRoot2->left) && isSubtree(pRoot1->right, pRoot2->right); } bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { bool result = false; if (pRoot1 != NULL && pRoot2 != NULL) { if (pRoot1->val == pRoot2->val) { result = isSubtree(pRoot1, pRoot2); } if (!result) result = HasSubtree(pRoot1->left, pRoot2); if (!result) result = HasSubtree(pRoot1->right, pRoot2); } return result; }
标签:要求 bool nbsp b树 return code root 相等 number
原文地址:https://www.cnblogs.com/veis/p/12623800.html