-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathw-tree-binary-DepthFirstValues.js
53 lines (47 loc) · 1.17 KB
/
w-tree-binary-DepthFirstValues.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
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// a
// / \
// b c
// / \ \
// d e f
const depthFirstValues = (root) => {
if (!root) return [];
console.log(root);
const left = depthFirstValues(root.left); // b,d,e
const right = depthFirstValues(root.right); // c,f
// console.log(left);
console.log("-----------");
console.log([root.val, ...left, ...right]);
};
// const depthFirstValues = (root) => {
// if (!root) return false;
// const stack = [root];
// const result = [];
// // console.log(stack);
// while (stack.length > 0) {
// const current = stack.pop();
// console.log(current.val);
// result.push(current.val);
// if (current.right) stack.push(current.right);
// if (current.left) stack.push(current.left);
// }
// console.log(result);
// };
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;
depthFirstValues(a);