【leetcode】剑指offer 26. 树的子结构,利用递归进行匹配

原题传送门
利用递归对于A树进行前序遍历,在前序遍历的同时匹配B树,发现成功后返回true,否则返回false

/**
 * 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 recur(TreeNode* A, TreeNode* B) {
     
        if(B == nullptr) return true;
        if(A == nullptr || A->val != B->val) return false;
        return recur(A->left, B->left) && recur(A->right, B->right);
    }
    bool isSubStructure(TreeNode* A, TreeNode* B) {
     
        return (A != nullptr && B != nullptr) && (recur(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B));
    }
};

你可能感兴趣的:(算法模板笔记,leetcode,算法,c++)