[剑指offer]JT17---树的子结构(树的比较都是递归)

剑指offer第十七题

题目如下

在这里插入图片描述

思路与代码

首先,有一个是空树就返回false
然后,递归比较三部分,两个树,第一个树左结构和第二个树,第一个树右结构和第二个树
递归比较中,就是先比较根值,再返回两个树的子结构比较与值

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
    
    
public:
    bool helper(TreeNode* root1,TreeNode* root2){
    
    
        if(root2==NULL) return true;
        if(root1==NULL) return false;
        if(root1->val==root2->val){
    
    
            return helper(root1->left,root2->left)&&helper(root1->right,root2->right);
        }else
            return false;
    }
    bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
    
    
        if(pRoot1==nullptr||pRoot2==nullptr) return false;
        return helper(pRoot1,pRoot2)||HasSubtree(pRoot1->left,pRoot2)||HasSubtree(pRoot1->right,pRoot2);
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42136832/article/details/114519096