
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.
1public class Solution {
2 public bool 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
8 private bool IsIdentical(TreeNode s, TreeNode t) {
9 if (s == null && t == null) return true;
10 if (s == null || t == null) return false;
11 return s.val == t.val && IsIdentical(s.left, t.left) && IsIdentical(s.right, t.right);
12 }
13}The C# solution utilizes recursion with two functions: IsSubtree performs tree traversal, while IsIdentical checks if the trees rooted at the current pair of nodes are identical.
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.
1class
Uses StringBuilder for efficient string concatenation while performing a preorder traversal; employs .contains to check if the serialized subRoot appears within the root's serialization.