-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path094_inorderTraversal.js
More file actions
43 lines (38 loc) · 929 Bytes
/
Copy path094_inorderTraversal.js
File metadata and controls
43 lines (38 loc) · 929 Bytes
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
/**
* https://leetcode.cn/problems/binary-tree-inorder-traversal/
* 二叉树的中序遍历
* easy
*/
// 递归
var inorderTraversal = function (root) {
if (!root) return [];
const left = inorderTraversal(root.left);
const right = inorderTraversal(root.right);
return [...left, root.val, ...right]
}
// var inorderTraversal = function (root) {
// if (!root) return [];
// const dfs = p => {
// if (p.left) dfs(p.left);
// res.push(p.val);
// if (p.right) dfs(p.right);
// }
// const res = [];
// dfs();
// return res;
// }
// 非递归
var inorderTraversal = function(root) {
if (root == null) return [];
const res = [], 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;
};