-
Notifications
You must be signed in to change notification settings - Fork 0
/
94-二叉树中序遍历.js
49 lines (44 loc) · 1.04 KB
/
94-二叉树中序遍历.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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
const { worker } = require("cluster");
// --------------------- 迭代 -------------------------- //
var inorderTraversal = function(root) {
let stack = [], curr = root;
let res = [];
while(curr != null || stack.length != 0) {
while(curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.push(curr.val);
curr = curr.right;
}
return res;
};
// --------------------------- 递归 ------------------------ //
const inorderTraversal = function(root) {
let res = [];
helper(root, res);
return res;
}
const helper = function (root, res) {
if(root != null) {
if(root.left != null) {
helper(root.left, res);
}
res.push(root.val);
if(root.right != null) {
helper(root.right, res);
}
}
}