Skip to content

Commit f1be469

Browse files
committed
Add solution #549
1 parent fa5abdb commit f1be469

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -534,6 +534,7 @@
534534
546|[Remove Boxes](./solutions/0546-remove-boxes.js)|Hard|
535535
547|[Number of Provinces](./solutions/0547-number-of-provinces.js)|Medium|
536536
548|[Split Array with Equal Sum](./solutions/0548-split-array-with-equal-sum.js)|Hard|
537+
549|[Binary Tree Longest Consecutive Sequence II](./solutions/0549-binary-tree-longest-consecutive-sequence-ii.js)|Medium|
537538
551|[Student Attendance Record I](./solutions/0551-student-attendance-record-i.js)|Easy|
538539
552|[Student Attendance Record II](./solutions/0552-student-attendance-record-ii.js)|Hard|
539540
553|[Optimal Division](./solutions/0553-optimal-division.js)|Medium|
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* 549. Binary Tree Longest Consecutive Sequence II
3+
* https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, return the length of the longest consecutive path in the tree.
7+
*
8+
* A consecutive path is a path where the values of the consecutive nodes in the path differ by one.
9+
* This path can be either increasing or decreasing.
10+
* - For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is
11+
* not valid.
12+
*
13+
* On the other hand, the path can be in the child-Parent-child order, where not necessarily be
14+
* parent-child order.
15+
*/
16+
17+
/**
18+
* Definition for a binary tree node.
19+
* function TreeNode(val, left, right) {
20+
* this.val = (val===undefined ? 0 : val)
21+
* this.left = (left===undefined ? null : left)
22+
* this.right = (right===undefined ? null : right)
23+
* }
24+
*/
25+
/**
26+
* @param {TreeNode} root
27+
* @return {number}
28+
*/
29+
var longestConsecutive = function(root) {
30+
let maxLength = 0;
31+
traverse(root);
32+
return maxLength;
33+
34+
function traverse(node) {
35+
if (!node) return [0, 0];
36+
37+
let inc = 1;
38+
let dec = 1;
39+
40+
if (node.left) {
41+
const [leftInc, leftDec] = traverse(node.left);
42+
if (node.val === node.left.val + 1) {
43+
dec = Math.max(dec, leftDec + 1);
44+
} else if (node.val === node.left.val - 1) {
45+
inc = Math.max(inc, leftInc + 1);
46+
}
47+
}
48+
49+
if (node.right) {
50+
const [rightInc, rightDec] = traverse(node.right);
51+
if (node.val === node.right.val + 1) {
52+
dec = Math.max(dec, rightDec + 1);
53+
} else if (node.val === node.right.val - 1) {
54+
inc = Math.max(inc, rightInc + 1);
55+
}
56+
}
57+
58+
maxLength = Math.max(maxLength, inc + dec - 1);
59+
return [inc, dec];
60+
}
61+
};

0 commit comments

Comments
 (0)