-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
83 lines (73 loc) · 2.53 KB
/
main.cpp
File metadata and controls
83 lines (73 loc) · 2.53 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Source: https://leetcode.com/problems/binary-tree-longest-consecutive-sequence
// Title: Binary Tree Longest Consecutive Sequence
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given the `root` of a binary tree, return the length of the longest **consecutive sequence path**.
//
// A **consecutive sequence path** is a path where the values **increase by one** along the path.
//
// Note that the path can start **at any node** in the tree, and you cannot go from a node to its parent in the path.
//
// **Example 1:**
// https://assets.leetcode.com/uploads/2021/03/14/consec1-1-tree.jpg
//
// ```
// Input: root = [1,null,3,2,4,null,null,null,5]
// Output: 3
// Explanation: Longest consecutive sequence path is 3-4-5, so return 3.
// ```
//
// **Example 2:**
// https://assets.leetcode.com/uploads/2021/03/14/consec1-2-tree.jpg
//
// ```
// Input: root = [2,null,3,2,null,1]
// Output: 2
// Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.
// ```
//
// **Constraints:**
//
// - The number of nodes in the tree is in the range `[1, 3 * 10^4]`.
// - `-3 * 10^4 <= Node.val <= 3 * 10^4`
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int longestConsecutive(TreeNode *root) {
auto [_, ans] = longestConsecutive_(root);
return ans;
}
// Returns current max length and global max length
pair<int, int> longestConsecutive_(TreeNode *root) {
auto currLen = 1;
auto globalLen = 1;
if (root->left) {
auto [leftLen, leftGlobalLen] = longestConsecutive_(root->left);
globalLen = max(globalLen, leftGlobalLen);
if (root->left->val == root->val + 1) {
currLen = max(currLen, leftLen + 1);
}
}
if (root->right) {
auto [rightLen, rightGlobalLen] = longestConsecutive_(root->right);
globalLen = max(globalLen, rightGlobalLen);
if (root->right->val == root->val + 1) {
currLen = max(currLen, rightLen + 1);
}
}
globalLen = max(globalLen, currLen);
return {currLen, globalLen};
}
};