子树和子结构

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AK_97_CT/article/details/87025823

子树

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
        if(!pRoot1||!pRoot2) return false;
        if(Part(pRoot1,pRoot2)) return true;
        return isSubtree(pRoot1->left,pRoot2)||isSubtree(pRoot1->right,pRoot2);
    }
    bool Part(TreeNode* s,TreeNode* t)
    { 
        if(!t&&!s) return true;
        if(!t||!s) return false;
        if(t->val!=s->val) return false;
        return Part(s->left,t->left)&&Part(s->right,t->right);
    }
};

子结构

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
        if(!pRoot1||!pRoot2) return false;
        if(isPart(pRoot1,pRoot2)) return true;
        return hasSubtree(pRoot1->left,pRoot2)||hasSubtree(pRoot1->right,pRoot2);
    }
    bool isPart(TreeNode* s, TreeNode* t)
    {
        if(!t) return true;
        if(!s||s->val!=s->val) return false;
        return isPart(s->left,t->left)&&isPart(s->right,t->right);
    }
    
};

猜你喜欢

转载自blog.csdn.net/AK_97_CT/article/details/87025823