Skip to content

Commit 152cd2b

Browse files
committedFeb 5, 2025
Add solution #257
1 parent acfd52c commit 152cd2b

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@
206206
237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy|
207207
238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium|
208208
242|[Valid Anagram](./0242-valid-anagram.js)|Easy|
209+
257|[Binary Tree Paths](./0257-binary-tree-paths.js)|Easy|
209210
258|[Add Digits](./0258-add-digits.js)|Easy|
210211
260|[Single Number III](./0260-single-number-iii.js)|Medium|
211212
263|[Ugly Number](./0263-ugly-number.js)|Easy|

‎solutions/0257-binary-tree-paths.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 257. Binary Tree Paths
3+
* https://leetcode.com/problems/binary-tree-paths/
4+
* Difficulty: Easy
5+
*
6+
* Given the root of a binary tree, return all root-to-leaf paths in any order.
7+
*
8+
* A leaf is a node with no children.
9+
*/
10+
11+
/**
12+
* Definition for a binary tree node.
13+
* function TreeNode(val, left, right) {
14+
* this.val = (val===undefined ? 0 : val)
15+
* this.left = (left===undefined ? null : left)
16+
* this.right = (right===undefined ? null : right)
17+
* }
18+
*/
19+
/**
20+
* @param {TreeNode} root
21+
* @return {string[]}
22+
*/
23+
var binaryTreePaths = function(root) {
24+
return tranverse(root);
25+
};
26+
27+
function tranverse(node, path = [], result = []) {
28+
if (!node) return;
29+
path.push(node.val.toString());
30+
if (!node.left && !node.right) {
31+
result.push(path.join('->'));
32+
} else {
33+
tranverse(node.left, path.slice(), result);
34+
tranverse(node.right, path.slice(), result);
35+
}
36+
return result;
37+
}

0 commit comments

Comments
 (0)
Please sign in to comment.