-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-postorder-traversal.js
More file actions
49 lines (44 loc) · 1.11 KB
/
binary-tree-postorder-traversal.js
File metadata and controls
49 lines (44 loc) · 1.11 KB
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, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* 二叉树的后序遍历 (先访问节点的后代节点,再访问节点本身)
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function (root) {
// 1. 递归
const result = [];
const postOrderTraversalNode = (node) => {
if (node) {
postOrderTraversalNode(node.left);
postOrderTraversalNode(node.right);
result.push(node.val);
}
};
postOrderTraversalNode(root);
return result;
// 2. 迭代
// return postOrderTraversalIterate(root);
};
// 后序遍历
// 中右左
// => reverse
// 左右中
function postOrderTraversalIterate(root) {
const result = [];
const stack = [];
root && stack.push(root);
while (stack.length > 0) {
const node = stack.pop();
result.push(node.val);
node.left && stack.push(node.left);
node.right && stack.push(node.right);
}
return result.reverse();
}