[leetcode] B树是不是A树的子结构

给定两棵二叉树 tree1tree2,判断 tree2 是否以 tree1 的某个节点为根的子树具有 相同的结构和节点值

注意,空树 不会是以 tree1 的某个节点为根的子树具有 相同的结构和节点值

示例 1:

复制代码
输入:tree1 = [1,7,5], tree2 = [6,1]
输出:false
解释:tree2 与 tree1 的一个子树没有相同的结构和节点值。

示例 2:

复制代码
输入:tree1 = [3,6,7,1,8], tree2 = [6,1]
输出:true
解释:tree2 与 tree1 的一个子树拥有相同的结构和节点值。即 6 - > 1。
复制代码
/**
 * 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 != nullptr && B != nullptr) && (recur(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B));
    }
private:
    bool recur(TreeNode* A, TreeNode* B) {
        if(B == nullptr) return true;
        if(A == nullptr) return false;
        return  A->val != B->val && recur(A->left, B->left) && recur(A->right, B->right);
    }
};
相关推荐
im_AMBER几秒前
Leetcode 114 链表中的下一个更大节点 | 删除排序链表中的重复元素 II
算法·leetcode
xhbaitxl13 分钟前
算法学习day38-动态规划
学习·算法·动态规划
多恩Stone13 分钟前
【3D AICG 系列-6】OmniPart 训练流程梳理
人工智能·pytorch·算法·3d·aigc
历程里程碑16 分钟前
普通数组----轮转数组
java·数据结构·c++·算法·spring·leetcode·eclipse
pp起床16 分钟前
贪心算法 | part02
算法·leetcode·贪心算法
sin_hielo17 分钟前
leetcode 1653
数据结构·算法·leetcode
2501_9011478319 分钟前
面试必看:优势洗牌
笔记·学习·算法·面试·职场和发展
YuTaoShao28 分钟前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法二)排序 + 二分查找
数据结构·算法·leetcode
wangluoqi29 分钟前
26.2.6练习总结
数据结构·算法
Q741_14733 分钟前
C++ 优先级队列 大小堆 模拟 力扣 703. 数据流中的第 K 大元素 每日一题
c++·算法·leetcode·优先级队列·