-
Notifications
You must be signed in to change notification settings - Fork 0
/
257_Binary Tree Paths.js
49 lines (42 loc) · 1022 Bytes
/
257_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
// https://leetcode.com/problems/binary-tree-paths/description/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function (root) {
var paths = [];
var getPath = function (node, path) {
if (!node) return;
var tempPath = path ? path += '->' + node.val : node.val.toString();
if (node.left) {
getPath(node.left, tempPath);
}
if (node.right) {
getPath(node.right, tempPath);
}
if (!node.left && !node.right) {
paths.push(tempPath);
return;
}
}
getPath(root);
return paths;
};
var root = new TreeNode(3);
root.left = new TreeNode(9);
root.left.right = new TreeNode(4);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
console.log(binaryTreePaths(root));