572.另一朵花的子树(javascript)572.SubtreeofAnotherTree

原创
小哥 3年前 (2022-11-10) 阅读数 8 #大杂烩

给你两棵二叉树 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/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除