-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy path0094. Binary Tree Inorder Traversal.js
66 lines (58 loc) · 1.22 KB
/
0094. Binary Tree Inorder Traversal.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
// Given a binary tree, return the inorder traversal of its nodes' values.
//
// Example:
//
// Input: [1,null,2,3]
// 1
// \
// 2
// /
// 3
//
// Output: [1,3,2]
//
// Follow up: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
// 1) Recursion
// Time O(n), the time complexity is O(n) because the recursive function is T(n) = 2 * T(n / 2) + 1
// Space O(log n), n is number of nodes. The worst case space is O(n)
const inorderTraversal1 = (root) => {
const res = [];
const go = (node) => {
if (node == null) return;
go(node.left, res);
res.push(node.val);
go(node.right, res);
};
go(root);
return res;
};
// 2) Iteration using stack
// Time O(n)
// Space O(n)
const inorderTraversal = (root) => {
const st = [];
const res = [];
while (root != null || st.length > 0) {
// Drill left
while (root) {
st.push(root);
root = root.left;
}
// Print & go to right child
root = st.pop();
res.push(root.val);
root = root.right;
}
return res;
};