-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathw-tree-minValue.js
87 lines (71 loc) · 1.63 KB
/
w-tree-minValue.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// p: tree !== null
// r: num
// e:
// 3
// / \
// 11 4
// / \ \
// 4 -2 1
// Recursion
const treeMinValue = (root) => {
if (!root) return Infinity;
const left = treeMinValue(root.left);
const right = treeMinValue(root.right);
return Math.min(root.val, left, right);
};
// root = 3 => Math.min(? , root)
// root1 = 11 => Math.min(root, root1)
// root = null =>
// // BFS
// const treeMinValue = (root) => {
// let min = Infinity;
// const queue = [root];
// while (queue.length > 0) {
// const current = queue.shift();
// min = Math.min(current.val, min);
// current.left && queue.push(current.left);
// current.right && queue.push(current.right);
// }
// console.log(min);
// return min;
// };
// // DFS
// const treeMinValue = (root) => {
// let min = Infinity;
// const stack = [root];
// while (stack.length > 0) {
// const current = stack.pop();
// min = Math.min(current.val, min);
// current.left && stack.push(current.left);
// current.right && stack.push(current.right);
// }
// console.log(min);
// return min;
// };
// module.exports = {
// treeMinValue,
// };
const a = new Node(3);
const b = new Node(11);
const c = new Node(4);
const d = new Node(4);
const e = new Node(-2);
const f = new Node(1);
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
// 3
// / \
// 11 4
// / \ \
// 4 -2 1
treeMinValue(a); // -> -2