-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-040-treeIncludes.js
70 lines (53 loc) · 1.42 KB
/
structy-040-treeIncludes.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// https://structy.net/problems/tree-includes
class Node {
constructor(val) {
this.val = val;
this.right = null;
this.left = null;
}
}
// p: root of bi-tree
// r: boolean
// dfs: recursion : better
const treeIncludes = (root, target) => {
if (!root) return false;
if (root.val === target) return true;
return treeIncludes(root.right, target) || treeIncludes(root.left, target);
};
// // dfs: recursion: ok
// const treeIncludes = (root, target) => {
// if (!root) return false;
// if (root.val === target) return true;
// if (treeIncludes(root.right, target)) return true;
// if (treeIncludes(root.left, target)) return true;
// return false;
// };
const a = new Node("a");
const b = new Node("b");
const c = new Node("c");
const d = new Node("d");
const e = new Node("e");
const f = new Node("f");
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
// a
// / \
// b c
// / \ \
// d e f
treeIncludes(a, "e"); // -> true
// // bfs
// const treeIncludes = (root, target) => {
// if (!root) return false;
// const queue = [root];
// while (queue.length > 0) {
// let current = queue.shift();
// if (current.val === target) return true;
// current.right && queue.push(current.right);
// current.left && queue.push(current.left);
// }
// return false;
// };