-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path94.js
More file actions
85 lines (69 loc) · 1.45 KB
/
94.js
File metadata and controls
85 lines (69 loc) · 1.45 KB
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
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
const n1 = new TreeNode(1);
const n2 = new TreeNode(2);
const n3 = new TreeNode(3);
n1.right = n2;
n2.left = n3;
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function (root) {
// console.log(root);
const res = [];
const inorder = (r) => {
if (r) {
inorder(r.left);
res.push(r.val);
inorder(r.right);
}
};
inorder(root);
return res;
};
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function (root) {
// console.log(root);
const res = [];
const stack = [];
while (root || stack.length) {
while (root) {
stack.push(root);
root = root.left;
}
root = stack.pop();
res.push(root.val);
root = root.right;
}
return res;
};
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function (root) {
const WHITE = 0;
const GRAY = 1;
const res = [];
const stack = [[WHITE, root]];
while (stack.length) {
const [color, node] = stack.pop();
if (node === null) continue;
if (color === WHITE) {
stack.push([WHITE, node.right]);
stack.push([GRAY, node]);
stack.push([WHITE, node.left]);
} else {
res.push(node.val);
}
}
return res;
};
console.log(inorderTraversal(n1));