-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_110.js
44 lines (38 loc) Β· 949 Bytes
/
problem_110.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
// https://leetcode.com/problems/binary-tree-paths/
//
// O(N) Time complexity
// O(H) Space complexity
// N is the nodes in the tree and H is the height of the tree
/**
* Return all baths from root to leaves
* @param {TreeNode} root
* @return {number[][]}
*/
function findRootPaths(root) {
const finalList = [];
backtrack(root, finalList, []);
return list;
}
/**
* Backtracking algorithm
* @param {TreeNode} root
* @param {number[][]} finalList
* @param {number[]} currList
*/
function backtrack(root, finalList, currList) {
// Base case
if (root === null) return [];
// Current node value
currList.push(root.val);
// No child nodes
if (root.left === null && root.right === null) {
finalList.push([...currList]);
currList.pop();
return;
}
// Search for other routes
backtrack(root.left, finalList, currList);
backtrack(root.right, finalList, currList);
// Remove final
currList.pop();
}