其他分享
首页 > 其他分享> > LeetCode 572 Subtree of Another Tree

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;
    }
};

标签:right,TreeNode,val,572,Tree,tree,return,LeetCode,left
来源: https://www.cnblogs.com/xinyu04/p/16549330.html