xinyu04

导航

LeetCode 572 Subtree of Another Tree

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.

Solution

我们可以递归地去 \(check\) 针对每一个节点,遍历每一个节点我们使用 \(BFS\) 即可

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    bool check(TreeNode* s, TreeNode* t){
        if(!s && !t)return true;
        if(!s || !t)return false;
        if(s->val == t->val)
            return check(s->left, t->left) && check(s->right, t->right);
        else return false;
    }
public:
    bool isSubtree(TreeNode* root, TreeNode* subRoot) {
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            auto f = q.front(); q.pop();
            if(check(f, subRoot))return true;
            if(f->left)q.push(f->left);
            if(f->right)q.push(f->right);
        }
        return false;
    }
};

posted on 2022-08-04 04:27  Blackzxy  阅读(13)  评论(0编辑  收藏  举报