[LeetCode] Binary Tree Longest Consecutive Sequence

298. Binary Tree Longest Consecutive Sequence

Given the root of a binary tree, return the length of the longest consecutive sequence path.

The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path needs to be from parent to child (cannot be the reverse).

  • Time : O(n)
  • Space : O(1)
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
/**
* Definition for a binary tree node.
* 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, int seq = 1) {
if(!root) return 0;
int res = seq;
if(root->left) {
int diff = root->left->val - root->val;
if(diff != 1) {
res = max(res, longestConsecutive(root->left, 1));
} else {
res = max(res, longestConsecutive(root->left, seq + 1));
}
}

if(root->right) {
int diff = root->right->val - root->val;
if(diff != 1) {
res = max(res, longestConsecutive(root->right, 1));
} else {
res = max(res, longestConsecutive(root->right, seq + 1));
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/17/PS/LeetCode/binary-tree-longest-consecutive-sequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.