Skip to content

Commit dca7633

Browse files
committed
Add solution #298
1 parent 275f5bb commit dca7633

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,7 @@
286286
295|[Find Median from Data Stream](./solutions/0295-find-median-from-data-stream.js)|Hard|
287287
296|[Best Meeting Point](./solutions/0296-best-meeting-point.js)|Hard|
288288
297|[Serialize and Deserialize Binary Tree](./solutions/0297-serialize-and-deserialize-binary-tree.js)|Hard|
289+
298|[Binary Tree Longest Consecutive Sequence](./solutions/0298-binary-tree-longest-consecutive-sequence.js)|Medium|
289290
299|[Bulls and Cows](./solutions/0299-bulls-and-cows.js)|Medium|
290291
300|[Longest Increasing Subsequence](./solutions/0300-longest-increasing-subsequence.js)|Medium|
291292
301|[Remove Invalid Parentheses](./solutions/0301-remove-invalid-parentheses.js)|Hard|
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 298. Binary Tree Longest Consecutive Sequence
3+
* https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, return the length of the longest consecutive sequence path.
7+
*
8+
* A consecutive sequence path is a path where the values increase by one along the path.
9+
*
10+
* Note that the path can start at any node in the tree, and you cannot go from a node to its
11+
* parent in the path.
12+
*/
13+
14+
/**
15+
* Definition for a binary tree node.
16+
* function TreeNode(val, left, right) {
17+
* this.val = (val===undefined ? 0 : val)
18+
* this.left = (left===undefined ? null : left)
19+
* this.right = (right===undefined ? null : right)
20+
* }
21+
*/
22+
/**
23+
* @param {TreeNode} root
24+
* @return {number}
25+
*/
26+
var longestConsecutive = function(root) {
27+
let result = 0;
28+
traverse(root, root.val - 1, 0);
29+
return result;
30+
31+
function traverse(node, parentValue, length) {
32+
if (!node) return;
33+
34+
const currentLength = parentValue + 1 === node.val ? length + 1 : 1;
35+
result = Math.max(result, currentLength);
36+
37+
traverse(node.left, node.val, currentLength);
38+
traverse(node.right, node.val, currentLength);
39+
}
40+
};

0 commit comments

Comments
 (0)