剑指 Offer 26. 树的子结构

分析

isSsubStructure遍历A树,与B树做匹配
recur从A树当前节点与B树的每个节点做匹配,当B为空的时候说明匹配完成,当A、B当前节点的值不相等时匹配失败,否则继续匹配左右节点

作者:Luna_
链接:https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/solution/26er-cha-shu-by-luna_-28ki/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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