Skip to content

Commit d9bee7e

Browse files
authored
Merge pull request #563 from notauserx/572-Subtree-of-Another-Tree-csharp
Create 572-Subtree-of-Another-Tree.cs
2 parents ef902eb + bf63df6 commit d9bee7e

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public int val;
5+
* public TreeNode left;
6+
* public TreeNode right;
7+
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
8+
* this.val = val;
9+
* this.left = left;
10+
* this.right = right;
11+
* }
12+
* }
13+
*/
14+
public class Solution {
15+
public bool IsSameTree(TreeNode one, TreeNode another) {
16+
if (one == null || another == null)
17+
return one == another;
18+
19+
return
20+
one.val == another.val &&
21+
IsSameTree(one.left, another.left) &&
22+
IsSameTree(one.right, another.right);
23+
}
24+
public bool IsSubtree(TreeNode root, TreeNode subRoot) {
25+
if (subRoot == null) return true;
26+
if (root == null) return false;
27+
28+
var nodeToVisit = new Queue<TreeNode>();
29+
30+
nodeToVisit.Enqueue(root);
31+
32+
while (nodeToVisit.Count > 0) {
33+
var cur = nodeToVisit.Dequeue();
34+
var isSame = IsSameTree(cur, subRoot);
35+
if (isSame) return true;
36+
37+
if (cur.left != null)
38+
nodeToVisit.Enqueue(cur.left);
39+
if (cur.right != null)
40+
nodeToVisit.Enqueue(cur.right);
41+
}
42+
43+
return false;
44+
}
45+
}

0 commit comments

Comments
 (0)