-
Notifications
You must be signed in to change notification settings - Fork 130
/
Binary Tree Paths.js
57 lines (46 loc) · 941 Bytes
/
Binary Tree Paths.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
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
*/
/**
* 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 result = [];
getPaths(root, null, result);
return result;
};
function getPaths(node, curStr, result) {
if (node === null) {
return;
}
if (!curStr) {
curStr = '' + node.val;
} else {
curStr += '->' + node.val;
}
if (node.left) {
getPaths(node.left, curStr, result);
}
if (node.right) {
getPaths(node.right, curStr, result);
}
if (!node.left && !node.right) {
result.push(curStr);
}
}