Skip to content

Commit 67ec0c1

Browse files
committed
590. N 叉树的后序遍历
1 parent c6de2b4 commit 67ec0c1

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@
127127
|557|[反转字符串中的单词 III](https://leetcode.cn/problems/reverse-words-in-a-string-iii/)|[JavaScript](./algorithms/reverse-words-in-a-string-iii.js)|Easy|
128128
|566|[重塑矩阵](https://leetcode.cn/problems/reshape-the-matrix/)|[JavaScript](./algorithms/reshape-the-matrix.js)|Easy|
129129
|589|[N 叉树的前序遍历](https://leetcode.cn/problems/n-ary-tree-preorder-traversal/)|[JavaScript](./algorithms/n-ary-tree-preorder-traversal.js)|Easy|
130+
|590|[N 叉树的后序遍历](https://leetcode.cn/problems/n-ary-tree-postorder-traversal/)|[JavaScript](./algorithms/n-ary-tree-postorder-traversal.js)|Easy|
130131
|598|[范围求和 II](https://leetcode.cn/problems/range-addition-ii/)|[JavaScript](./algorithms/range-addition-ii.js)|Easy|
131132
|617|[合并二叉树](https://leetcode.cn/problems/merge-two-binary-trees/)|[JavaScript](./algorithms/merge-two-binary-trees.js)|Easy|
132133
|628|[三个数的最大乘积](https://leetcode.cn/problems/maximum-product-of-three-numbers/)|[JavaScript](./algorithms/maximum-product-of-three-numbers.js)|Easy|
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* // Definition for a Node.
3+
* function Node(val,children) {
4+
* this.val = val;
5+
* this.children = children;
6+
* };
7+
*/
8+
9+
/**
10+
* @param {Node|null} root
11+
* @return {number[]}
12+
*/
13+
var postorder = function (root) {
14+
// DFS
15+
const result = [];
16+
const dfs = (node) => {
17+
if (node) {
18+
const children = node.children;
19+
children.forEach((child) => {
20+
dfs(child);
21+
});
22+
result.push(node.val);
23+
}
24+
};
25+
26+
dfs(root);
27+
28+
return result;
29+
30+
// BFS
31+
// return bfs(root);
32+
};
33+
34+
// 后序遍历 左右中
35+
// 先序遍历(中左右) -> 中右左(调整代码顺序) -> 左右中(反转结果)
36+
37+
function bfs(root) {
38+
if (!root) return [];
39+
const result = [];
40+
const stack = [];
41+
stack.push(root);
42+
43+
while (stack.length) {
44+
const node = stack.pop();
45+
result.push(node.val);
46+
const children = node.children;
47+
children.forEach((child) => {
48+
stack.push(child);
49+
});
50+
}
51+
52+
return result.reverse();
53+
}

0 commit comments

Comments
 (0)