-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0549-binary-tree-longest-consecutive-sequence-ii.js
More file actions
66 lines (56 loc) · 1.64 KB
/
0549-binary-tree-longest-consecutive-sequence-ii.js
File metadata and controls
66 lines (56 loc) · 1.64 KB
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
58
59
60
61
62
63
64
65
66
/**
* Binary Tree Longest Consecutive Sequence II
* Time Complexity: O(N)
* Space Complexity: O(H)
*/
var longestConsecutive = function (root) {
let overallMaxPathLength = 0;
function calculateNodePaths(currentNode) {
if (!currentNode) {
return [0, 0];
}
let nodeIncreasingSequence = 1;
let nodeDecreasingSequence = 1;
if (currentNode.left) {
const [leftAscendingLength, leftDescendingLength] = calculateNodePaths(
currentNode.left,
);
if (currentNode.val === currentNode.left.val + 1) {
nodeDecreasingSequence = Math.max(
nodeDecreasingSequence,
leftDescendingLength + 1,
);
}
if (currentNode.val === currentNode.left.val - 1) {
nodeIncreasingSequence = Math.max(
nodeIncreasingSequence,
leftAscendingLength + 1,
);
}
}
if (currentNode.right) {
const [rightAscendingLength, rightDescendingLength] = calculateNodePaths(
currentNode.right,
);
if (currentNode.val === currentNode.right.val + 1) {
nodeDecreasingSequence = Math.max(
nodeDecreasingSequence,
rightDescendingLength + 1,
);
}
if (currentNode.val === currentNode.right.val - 1) {
nodeIncreasingSequence = Math.max(
nodeIncreasingSequence,
rightAscendingLength + 1,
);
}
}
overallMaxPathLength = Math.max(
overallMaxPathLength,
nodeIncreasingSequence + nodeDecreasingSequence - 1,
);
return [nodeIncreasingSequence, nodeDecreasingSequence];
}
calculateNodePaths(root);
return overallMaxPathLength;
};