Skip to content

Commit 1252dbf

Browse files
authored
Create 298. Binary Tree Longest Consecutive Sequence.cpp
1 parent 89a687a commit 1252dbf

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// DFS
2+
class Solution {
3+
public:
4+
int longestConsecutive(TreeNode* root) {
5+
int maxlen = 0;
6+
DFS(NULL, root, 1, maxlen);
7+
return maxlen;
8+
}
9+
10+
void DFS(TreeNode* from, TreeNode* cur, int len, int& maxlen){
11+
if(!cur) return;
12+
len = (from && cur->val == from->val + 1) ? len + 1 : 1;
13+
maxlen = max(maxlen, len);
14+
DFS(cur, cur->left, len, maxlen);
15+
DFS(cur, cur->right, len, maxlen);
16+
}
17+
};
18+
19+
// BFS
20+
class Solution {
21+
public:
22+
int longestConsecutive(TreeNode* root) {
23+
if(!root) return 0;
24+
deque<pair<TreeNode*, int>>q;
25+
q.push_back({root, 1});
26+
int maxlen = 0;
27+
while(!q.empty()){
28+
auto p = q.front();
29+
q.pop_front();
30+
if(p.first->left) q.push_back({p.first->left, (p.first->left->val == p.first->val + 1) ? p.second + 1 : 1});
31+
if(p.first->right) q.push_back({p.first->right, (p.first->right->val == p.first->val + 1) ? p.second + 1 : 1});
32+
maxlen = max(maxlen, p.second);
33+
}
34+
return maxlen;
35+
}
36+
};

0 commit comments

Comments
 (0)