Leetcode 144 - Binary tree preorder traversal

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

Example

img

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

Recursion:

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
/**
* 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 preorderTraversal = function(root) {
let ans = [];
dfs(root, ans);
return ans;
};

function dfs(root, result) {
if (!root) {
return;
}
result.push(root.val);
dfs(root.left, result);
dfs(root.right, result);
}

Iteratiion:

1
2
3
4
5
6
7
8
9
10
var preorderTraversal = function(root, result = []) {
let stack = [root];
while (stack.length) {
let cur = stack.pop();
result.push(cur.val);
preorderTraversal(root.left, result);
preorderTraversal(root.right, result);
}
return result;
}