-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreeLongestConsecutiveSequence.cpp
85 lines (84 loc) · 2.44 KB
/
BinaryTreeLongestConsecutiveSequence.cpp
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
84
85
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode * root, int prev , int curr, int & res){
res = max(res, curr);
if(root!= nullptr){
if(prev + 1 == root->val){
dfs(root->left, root->val, curr + 1, res);
dfs(root->right, root->val, curr + 1, res);
}else{
dfs(root->left, root->val, 1, res);
dfs(root->right, root->val, 1, res);
}
}
}
int longestConsecutive(TreeNode* root) {
std::ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
if(root == nullptr || (!root->left && !root->right)){
return root==nullptr ? 0 : 1;
}
int res = INT_MIN;
int prev = INT_MIN;
dfs(root, prev, 1, res);
return res;
}
};
//Approach 2 : using iterative BFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode * root, int prev , int curr, int & res){
res = max(res, curr);
if(root!= nullptr){
if(prev + 1 == root->val){
dfs(root->left, root->val, curr + 1, res);
dfs(root->right, root->val, curr + 1, res);
}else{
dfs(root->left, root->val, 1, res);
dfs(root->right, root->val, 1, res);
}
}
}
int longestConsecutive(TreeNode* root) {
std::ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
if(root == nullptr){
return 0;
}
int res = 1;
queue<pair<TreeNode *, int>> q;
q.push(make_pair(root, 1));
while(!q.empty()){
auto curr = q.front();
if(curr.first->left){
q.push(make_pair(curr.first->left, curr.first->left->val == curr.first->val +1 ? curr.second + 1 : 1));
}
if(curr.first->right){
q.push(make_pair(curr.first->right, curr.first->right->val == curr.first->val +1 ? curr.second + 1 : 1));
}
q.pop();
res = max(res, curr.second);
}
return res;
}
};