572. 另一棵树的子树(javascript)572. Subtree of Another Tree

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

二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。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.

示例 1:

请添加图片描述

输入:root = [3,4,5,1,2], subRoot = [4,1,2]
输出:true

示例 2:请添加图片描述

输入:root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
输出:false

提示:

root 树上的节点数量范围是 [1, 2000]
subRoot 树上的节点数量范围是 [1, 1000]
-104 <= root.val <= 104
-104 <= subRoot.val <= 104

定义isSameTree()用来判断两个树是否相同
首先判断s和t是否相同,相同返回true
不相同就递归判断s的左右子树是否和t相同

解题思路

  1. root==null时,不存在包含关系,返回flase
  2. 判断两个树是否相同,相同返回true,
    不相同-遍历root的左子树
    不相同-遍历root的右子树
  3. 如何判断两个树是否相同:
    !p&&!q为true,相同
    p,q存在,同时两个值相同,递归左子树,递归右子树
    其他情况,返回false
var isSubtree = function (root, subRoot) {
    if (root == null) return false
    if (isSameTree(root, subRoot)) return true
    return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)
};

// 判断两个树是否相同
const isSameTree = (p, q) => {
    if(!p&&!q) return true
    if(p&&q&&p.val===q.val&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)) return true
    return false

};

leetcode:https://leetcode-cn.com/problems/subtree-of-another-tree/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值