-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-040-treeIncludes-2.js
54 lines (41 loc) · 1.15 KB
/
structy-040-treeIncludes-2.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
// class Node {
// constructor(val) {
// this.val = val;
// this.left = null;
// this.right = null;
// }
// }
// p: root of bi tree
// r: boolean
// dfs recursion O(nodes) O(n)
const treeIncludes = (root, target) => {
if (!root) return false;
if (root.val === target) return true;
const left = treeIncludes(root.left, target);
const right = treeIncludes(root.right, target);
return left || right;
};
// // dfs recursion O(nodes) O(n)
// const treeIncludes = (root, target) => {
// if (!root) return false;
// if (root.val === target) return true;
// const left = treeIncludes(root.left, target);
// const right = treeIncludes(root.right, target);
// if (left || right) return true;
// return false;
// };
// // dfs iteration O(nodes) O(n)
// const treeIncludes = (root, target) => {
// if (!root) return false;
// const stack = [root]
// while (stack.length > 0) {
// const current = stack.pop()
// if (current.val === target) return true;
// current.left && stack.push(current.left);
// current.right && stack.push(current.right);
// }
// return false;
// };
module.exports = {
treeIncludes,
};