[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.
Example 1:
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
Example 2:
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false
Constraints:
The number of nodes in the root tree is in the range [1, 2000].
The number of nodes in the subRoot tree is in the range [1, 1000].
-104 <= root.val <= 104
-104 <= subRoot.val <= 104
另一个树的子树。
给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false 。
二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/subtree-of-another-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
题意是给两个树 root 和 subRoot,判断 subRoot 是否是 root 的子树。如果两者相同,也可以视为 subRoot 是 root 的子树。
这个题的思路跟100题same tree非常像。既然是问 subRoot 是否是 root 的子树,那也就意味着 root 这棵树比 subRoot 要大,或者最多相同,所以就可以按照100题的思路递归比较
- root 的左子树和右子树是否分别和 subRoot 一样
- root 是否和 subRoot 是相同的树
复杂度
时间O(n)
空间O(n)
代码
Java实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
// corner case
if (root == null) {
return false;
}
if (subRoot == null) {
return true;
}
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot) || helper(root, subRoot);
}
private boolean helper(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
if (p.val != q.val) {
return false;
}
return helper(p.left, q.left) && helper(p.right, q.right);
}
}
JavaScript实现
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} s
* @param {TreeNode} t
* @return {boolean}
*/
var isSubtree = function (s, t) {
if (s === null) {
return false;
}
if (t === null) {
return true;
}
if (isSameTree(s, t)) {
return true;
}
return isSubtree(s.left, t) || isSubtree(s.right, t) || isSameTree(s, t);
};
var isSameTree = function (s, t) {
if (s === null && t === null) {
return true;
}
if (s === null || t === null) {
return false;
}
if (s.val != t.val) {
return false;
}
return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
};