中序遍历

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
// Way1. 栈结构实现
function inOrder(root) {
var res = [];
var stack = [];
var p = root;
while (p || stack.length > 0) {
while (p) {
stack.push(p);
p = p.left;
}
p = stack.pop();
res.push(p.node);
p = p.right
}
return res
}

// Way2. 递归实现
function inOrderCore(root, res) {
if (!root) {
return
}
inOrderCore(root.left, res);
res.push(root.node);
inOrderCore(root.right, res);
}

function inOrder2(root) {
var res = [];
inOrderCore(root, res);
return res;
}