树和二叉树_11

发布于:2025-02-13 ⋅ 阅读:(87) ⋅ 点赞:(0)


一、leetcode-572

另一棵树的子树
给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false 。

二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。

请添加图片描述

样例输入:root = [3,4,5,1,2], subRoot = [4,1,2]

样例输出: true

请添加图片描述
样例输入:root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]

样例输出: false


二、题解

1.引库

 #include <iostream>
 #include <cstdio>
 #include <cstdlib>
 #include <queue>
 #include <stack>
 #include <algorithm>
 #include <string>
 #include <map>
 #include <set>
 #include <vector>
 using namespace std;
 

2.代码

/**
 * 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 {
public:
	bool match(TreeNode* root, TreeNode* subRoot){
		if(root==NULL) return subRoot==NULL;
		if(subRoot==NULL) return root==NULL;
		if(root->val!=subRoot->val) return false;
		return match(root->left,subRoot->left)&&match(root->right,subRoot->right);
	}
    bool isSubtree(TreeNode* root, TreeNode* subRoot) {
        if(root==NULL) return subRoot==NULL;
        if(subRoot==NULL) return false;
        if(root->val==subRoot->val&&match(root,subRoot)) return true;
        if(isSubtree(root->left,subRoot)) return true;
        if(isSubtree(root->right,subRoot)) return true;
        return false;
    }
};



网站公告

今日签到

点亮在社区的每一天
去签到