generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem52.cs
More file actions
45 lines (39 loc) · 1.39 KB
/
Problem52.cs
File metadata and controls
45 lines (39 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/subtree-of-another-tree/">Subtree of Another Tree</see>.
/// </summary>
public static class Problem52
{
/// <summary>
/// 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.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="root">Binary tree.</param>
/// <param name="subRoot">Binary subtree.</param>
/// <returns>True, if the binary tree contains the provided subtree.</returns>
public static bool IsSubtree(TreeNode? root, TreeNode? subRoot)
{
if (root == null && subRoot == null)
{
return true;
}
if (root == null || subRoot == null)
{
return false;
}
return TraverseSubtree(root, subRoot) || IsSubtree(root.Left, subRoot) || IsSubtree(root.Right, subRoot);
}
private static bool TraverseSubtree(TreeNode? root, TreeNode? subRoot)
{
if (root == null && subRoot == null)
{
return true;
}
if (root == null || subRoot == null)
{
return false;
}
return root.Val == subRoot.Val && TraverseSubtree(root.Left, subRoot.Left) && TraverseSubtree(root.Right, subRoot.Right);
}
}