Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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 {
- int maxLen = 0;
- public:
- int longestConsecutive(TreeNode* root) {
- dfs(root);
- return maxLen;
- }
- vector<int> dfs(TreeNode *root){
- if(!root) return {0,0};
- vector<int> curr(2, 1);
- if(root->left){
- vector<int> left = dfs(root->left);
- if(root->val == root->left->val+1)
- curr[1] = left[1]+1;
- else if(root->val == root->left->val-1)
- curr[0] = left[0]+1;
- }
- if(root->right){
- vector<int> right = dfs(root->right);
- if(root->val == root->right->val+1){
- curr[1] = max(curr[1], right[1]+1);
- }
- else if(root->val == root->right->val-1){
- curr[0] = max(curr[0], right[0]+1);
- }
- }
- maxLen = max(maxLen, curr[0]+curr[1]-1);
- return curr;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement