-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreecontains.js
56 lines (42 loc) · 845 Bytes
/
treecontains.js
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
46
47
48
49
50
51
52
53
54
55
56
/*You have two very large binary trees: T1 with millions of nodes and T2 with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1. */
"use strict";
function treeContains(t1, t2) {
if(t1 === t2) {
return true;
}
if(!t1) {
return false;
}
if(!t2) {
return true;
}
return subTreeCheck(t1, t2);
}
function subTreeCheck(t1, t2) {
if(t1 === t2) {
return true;
}
if(!t1) {
return false;
}
if(t1.value == t2.value) {
if(matchTree(t1, t2)) {
return true;
}
}
return subTreeCheck(t1.left, t2) || subTreeCheck(t1.right, t2);
}
function matchTree(t1, t2) {
if(t1 === t2) {
return true;
}
if(!t1 || !t2) {
return false;
}
if(t1.value == t2.value) {
return matchTree(t1.left, t2.left) && matchTree(t1.right, t2.right);
} else {
return false;
}
}
module.exports = treeContains;