Advertisement
nikunjsoni

549

May 4th, 2021
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13.     int maxLen = 0;
  14. public:
  15.     int longestConsecutive(TreeNode* root) {
  16.         dfs(root);
  17.         return maxLen;
  18.     }
  19.    
  20.     vector<int> dfs(TreeNode *root){
  21.         if(!root) return {0,0};
  22.         vector<int> curr(2, 1);
  23.        
  24.         if(root->left){
  25.             vector<int> left = dfs(root->left);
  26.             if(root->val == root->left->val+1)
  27.                 curr[1] = left[1]+1;
  28.             else if(root->val == root->left->val-1)
  29.                 curr[0] = left[0]+1;
  30.         }
  31.         if(root->right){
  32.             vector<int> right = dfs(root->right);
  33.             if(root->val == root->right->val+1){
  34.                 curr[1] = max(curr[1], right[1]+1);
  35.             }
  36.             else if(root->val == root->right->val-1){
  37.                 curr[0] = max(curr[0], right[0]+1);
  38.             }
  39.         }
  40.         maxLen = max(maxLen, curr[0]+curr[1]-1);
  41.         return curr;
  42.     }
  43.    
  44. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement