Leetcode 145 - Binary tree postorder traversal

Given the root of a binary tree, return the postorder traversal of its nodes’ values.
Example

img

1
2
Input: root = [1,null,2,3]
Output: [3,2,1]

Iterative:

1
2
3
4
5
6
7
8
9
10
11
12
var postorderTraversal = function(root, result = []) {
if (!root) return result;
let stack = [root];
let cur = null;
while (stack.length) {
cur = stack.pop();
result.push(cur.val);
cur.left && stack.push(cur.left);
cur.right && stack.push(cur.right);
}
return result.reverse();
};

Recursive

1
2
3
4
5
6
7
8
9
10
11
var postorderTraversal = function(root) {
let result = [];
dfs(root, result);
return result;
};
function dfs(root, result) {
if (!root) return;
dfs(root.left, result);
dfs(root.right, result);
result.push(root.val);
}