剑指offer26.树的子结构(c++)


class Solution {
public:
    bool isSubStructure(TreeNode* A, TreeNode* B) {
        //A/B为空则返回false
        if( A == nullptr || B == nullptr) return false;
        //从A开始进行先序遍历
        return traversal( A, B ) || isSubStructure( A->left, B) || isSubStructure( A->right, B);
    }
    //判断B是否为A的子树
    bool traversal( TreeNode* A, TreeNode* B )
    {
        //B为空则说明遍历完B
        if( B == nullptr ) return true;
        //A为空则没遍历完B
        if( A == nullptr ) return false;
        return A->val == B->val && traversal( A->left, B->left ) && traversal( A->right, B->right );
    }
};