forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add solutions to lc problem: No.0298
No.0298.Binary Tree Longest Consecutive Sequence
- Loading branch information
Showing
8 changed files
with
396 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/Solution.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/** | ||
* 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 ans; | ||
|
||
int longestConsecutive(TreeNode* root) { | ||
ans = 1; | ||
dfs(root, nullptr, 1); | ||
return ans; | ||
} | ||
|
||
void dfs(TreeNode* root, TreeNode* p, int t) { | ||
if (!root) return; | ||
t = p != nullptr && p->val + 1 == root-> val ? t + 1 : 1; | ||
ans = max(ans, t); | ||
dfs(root->left, root, t); | ||
dfs(root->right, root, t); | ||
} | ||
}; |
Oops, something went wrong.