-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbinaryTreePaths.js
More file actions
40 lines (36 loc) · 870 Bytes
/
binaryTreePaths.js
File metadata and controls
40 lines (36 loc) · 870 Bytes
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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function(root) {
var preResults = [];
var findPaths = function(prevNode, buildUp){
if (prevNode === null){
return;
} else if (prevNode.right === null && prevNode.left === null){
buildUp.push(prevNode.val);
preResults.push(buildUp.slice());
buildUp.pop();
return;
}
buildUp.push(prevNode.val);
findPaths(prevNode.right, buildUp);
findPaths(prevNode.left, buildUp);
buildUp.pop();
}
findPaths(root, []);
var results = [];
for (var i = 0; i < preResults.length; i++){
if (preResults[i].length > 0){
results.push(preResults[i].join('->'));
}
}
return results;
};