剑指offer18 树的子结构

时间:2023-03-09 04:59:30
剑指offer18 树的子结构

另一种写法

class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
bool result = false;
if(pRoot1 != NULL && pRoot2 != NULL){
if(pRoot1->val == pRoot2->val)
result = HasSubCore(pRoot1,pRoot2);
if(!result)
result = HasSubCore(pRoot1->left,pRoot2) || HasSubCore(pRoot1->right,pRoot2);
}
return result;
}
bool HasSubCore(TreeNode* p1,TreeNode* p2){
if(p2 == NULL)
return true;
if(p1 == NULL)
return false;
if(p1->val != p2->val)
return false;
return HasSubCore(p1->left,p2->left) && HasSubCore(p1->right,p2->right);
}
};

必须是if(!result),不能用else,因为如果两个树的头是相同的,但左右却不同就会报错。这种情况应该是继续迭代第一个树的左右节点,但用else,就会直接进入第一个if并返回值了

{8,8,7,9,2,#,#,#,#,4,7},{8,9,2}用else就不行