-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
44 lines (42 loc) · 1022 Bytes
/
solution.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
/**
* 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) {
if (root === null) {
return []
}
let res = [],
paths = [
{
node: root,
path: String(root.val)
}
]
while (paths.length > 0) {
let path = paths.pop()
if (path.node.left === null && path.node.right === null) {
res.push(path.path)
}
if (path.node.left !== null) {
paths.push({
node: path.node.left,
path: path.path + '->' + String(path.node.left.val)
})
}
if (path.node.right !== null) {
paths.push({
node: path.node.right,
path: path.path + '->' + String(path.node.right.val)
})
}
}
return res
};