AcWing 37. 树的子结构(C++)- 二叉树

题目链接:https://www.acwing.com/problem/content/35/
题目如下:
在这里插入图片描述

/**
 * 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==NULL||pRoot2==NULL) return false;
        
        if(issub(pRoot1,pRoot2)) return true;//递归遍历当前节点
        else return hasSubtree(pRoot1->left,pRoot2)||hasSubtree(pRoot1->right,pRoot2);//通过找第一棵树的其他节点
    }
    
    bool issub(TreeNode* A,TreeNode* B){
    
    
        if(B==NULL) return true;//当B走完时,则为真
        
        if(A==NULL&&B!=NULL) return false;//B不为A的子树的情况,1、两棵树有一棵先遍历完成 2、两棵树都没遍历完,但值不相等
        if(A!=NULL&&B==NULL) return false;
        if(A->val!=B->val) return false;
        
        return issub(A->left,B->left)&&issub(A->right,B->right);//继续遍历其左右节点
    }
};

おすすめ

転載: blog.csdn.net/qq_40467670/article/details/121152432