-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinaryTreePostorderTraversal.js
52 lines (47 loc) · 1.24 KB
/
binaryTreePostorderTraversal.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
var postorderTraversal = function(root) {
if (!root) return [];
const res = [];
// 翻转单链表
const postMorrisReverseList = (root) => {
let cur = root;
let pre;
while (cur) {
let next = cur.right;
cur.right = pre;
pre = cur;
cur = next;
}
return pre;
};
// 打印函数
const postMorrisPrint = (root) => {
const reverseList = postMorrisReverseList(root);
let cur = reverseList;
while (cur) {
res.push(cur.val);
cur = cur.right;
}
postMorrisReverseList(reverseList);
};
let cur1 = root; // 遍历树的指针变量
let cur2; // 当前子树的最右节点
while(cur1) {
cur2 = cur1.left;
if(cur2) {
while (cur2.right && cur2.right !== cur1) {
cur2 = cur2.right;
}
if (!cur2.right) {
cur2.right = cur1;
cur1 = cur1.left;
continue;
} else {
cur2.right = null;
postMorrisPrint(cur1.left);
}
}
cur1 = cur1.right;
}
postMorrisPrint(root);
return res;
};