1
+ /* *
2
+ * Definition for a binary tree node.
3
+ * struct TreeNode {
4
+ * int val;
5
+ * TreeNode *left;
6
+ * TreeNode *right;
7
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8
+ * };
9
+ */
10
+ class Solution {
11
+ pair<int , int > longestConsecutive (TreeNode* root, int & longest) {
12
+ if (!root->left and !root->right ) {
13
+ longest = max (longest, 1 );
14
+ return {1 , 1 };
15
+ }
16
+ int incrSeqLeftLen = 1 , decSeqLeftLen = 1 , incrSeqRightLen = 1 , decSeqRightLen = 1 ;
17
+ if (root->left ) {
18
+ pair<int , int > leftSeqLen = longestConsecutive (root->left , longest);
19
+ if (root->left ->val + 1 == root->val ) {
20
+ incrSeqLeftLen = max (incrSeqLeftLen, leftSeqLen.first + 1 );
21
+ } else if (root->left ->val == root->val + 1 ) {
22
+ decSeqLeftLen = max (decSeqLeftLen, leftSeqLen.second + 1 );
23
+ }
24
+ }
25
+
26
+ if (root->right ) {
27
+ pair<int , int > rightSeqLen = longestConsecutive (root->right , longest);
28
+ if (root->right ->val + 1 == root->val ) {
29
+ incrSeqRightLen = max (incrSeqRightLen, rightSeqLen.first + 1 );
30
+ } else if (root->right ->val == root->val + 1 ) {
31
+ decSeqRightLen = max (decSeqRightLen, rightSeqLen.second + 1 );
32
+ }
33
+ }
34
+
35
+ longest = max (longest, max (incrSeqLeftLen + decSeqRightLen - 1 , decSeqLeftLen + incrSeqRightLen - 1 ));
36
+
37
+ return {max (incrSeqLeftLen, incrSeqRightLen), max (decSeqLeftLen, decSeqRightLen)};
38
+ }
39
+ public:
40
+ int longestConsecutive (TreeNode* root) {
41
+ if (!root) return 0 ;
42
+ int longest = INT_MIN;
43
+ longestConsecutive (root, longest);
44
+
45
+ return longest;
46
+ }
47
+ };
0 commit comments