-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostorderTraverse.js
85 lines (77 loc) · 1.91 KB
/
postorderTraverse.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*jshint node:true, white:true*/
var assert = require('assert'),
_ = require('./lib/underscore');
/**
* 后序遍历
* @method postorderTraverse
* @param {Object} tree
* @return {Array}
*/
function postorderTraverse(tree) {
var ret = [];
if (tree.left) ret = ret.concat(postorderTraverse(tree.left));
if (tree.right) ret = ret.concat(postorderTraverse(tree.right));
ret.push(tree.value);
return ret;
}
/**
* 非递归后序遍历
* @method postorderTraverseNonrecursive
* @param {Object} tree
* @return {Array}
*/
function postorderTraverseNonrecursive(tree) {
var ret = [],
stack = [],
root = [],
node = tree,
top;
do {
// 遍历左子树
while (node) {
stack.push(node);
node = node.left;
}
do {
top = stack.pop();
// 第二次出栈,说明已经遍历过
if (root.length && top === root[root.length - 1]) {
root.pop();
} else {
// 遍历右子树
if (top.right) {
stack.push(top);
root.push(top);
node = top.right;
break;
}
}
// 操作根结点
ret.push(top.value);
} while (stack.length || root.length)
} while (node)
return ret;
}
var tree = {
value: 'A',
left: {
value: 'B',
right: {
value: 'D',
left: {
value: 'E'
}
}
},
right: {
value: 'C',
left: {
value: 'F'
},
right: {
value: 'G'
}
}
}
assert.deepEqual(postorderTraverse(tree), ['E', 'D', 'B', 'F', 'G', 'C', 'A'], 'recursive failed');
assert.deepEqual(postorderTraverseNonrecursive(tree), ['E', 'D', 'B', 'F', 'G', 'C', 'A'], 'nonrecursive failed');