
Sponsored
Sponsored
This approach involves using a recursive function to traverse the root tree and checking for a matching subtree starting from every node. A helper function can be used to check if trees rooted at specific nodes are identical.
Time Complexity: O(N*M), where N is the number of nodes in the root tree and M is the number of nodes in subRoot tree.
Space Complexity: O(min(N, M)), depending on the tree height during recursion.
1class Solution {
2 public boolean isSubtree(TreeNode root, TreeNode subRoot) {
3 if (root == null) return false;
4 if (isIdentical(root, subRoot)) return true;
5 return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
6 }
7 public boolean isIdentical(TreeNode s, TreeNode t) {
8 if (s == null && t == null) return true;
9 if (s == null || t == null) return false;
10 return s.val == t.val && isIdentical(s.left, t.left) && isIdentical(s.right, t.right);
11 }
12}This Java solution uses recursion to traverse through each node of the main tree and checks if starting from that node, the two trees are identical using isIdentical.
Another approach to solving this problem is by converting the trees into their preorder traversal strings with marker symbols for nulls, and then checking if the subRoot string is a substring of the root string.
Time Complexity: O(N + M + N*M), where N and M are the sizes of the trees.
Space Complexity: O(N + M), for the preorder traversal strings.
1public class Solution {
public bool IsSubtree(TreeNode root, TreeNode subRoot) {
string rootStr = Preorder(root, new System.Text.StringBuilder()).ToString();
string subRootStr = Preorder(subRoot, new System.Text.StringBuilder()).ToString();
return rootStr.Contains(subRootStr);
}
private StringBuilder Preorder(TreeNode node, StringBuilder sb) {
if (node == null) {
sb.Append("null ");
return sb;
}
sb.Append(node.val).Append(' ');
Preorder(node.left, sb);
Preorder(node.right, sb);
return sb;
}
}The C# solution serializes the trees to preorder strings, including null representations, then checks if subRoot's string occurs in root's string using StringBuilder for flexibility.