Subtree of Another Tree easy
Problem Statement
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 with subRoot
and false
otherwise.
A subtree of a binary tree root
is a tree that consists of a node in root
and all of this node's descendants. The tree root
may contain multiple subtrees of the same structure and value with subRoot
.
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
Steps
- Recursive Approach: We'll use a recursive function to traverse the
root
tree. - Same Structure and Values Check: For each node in
root
, we'll compare it with thesubRoot
. This comparison involves checking if the node values match and recursively checking if the left and right subtrees match. We use a helper functionisSameTree
for this. - Base Cases:
- If
subRoot
is null, it means we've matched the structure, returntrue
. - If
root
is null butsubRoot
is not, there's no match, returnfalse
. - If the node values don't match, return
false
.
- If
- Recursive Calls: Recursively compare the left and right subtrees of
root
andsubRoot
.
Explanation
The solution recursively checks if any subtree within root
is identical to subRoot
. The isSameTree
function provides a clean way to compare the structure and values of two trees. The main function iterates through root
to find a potential starting point for a matching subtree.
Code
using System;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public bool IsSubtree(TreeNode root, TreeNode subRoot) {
if (root == null) return false;
if (isSameTree(root, subRoot)) return true;
return IsSubtree(root.left, subRoot) || IsSubtree(root.right, subRoot);
}
private bool isSameTree(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 isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
Complexity
- Time Complexity: O(M * N), where M is the number of nodes in
root
and N is the number of nodes insubRoot
. In the worst case, we might comparesubRoot
with every node inroot
. - Space Complexity: O(M + N) in the worst case due to the recursive call stack. The depth of the recursion can be at most the height of the larger tree.