raghuvanshraj

1372.cpp

Jul 29th, 2021
547
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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 ans;
  14. public:
  15.     int _longestZigZag(TreeNode *root, bool dir) {
  16.         if (!root) {
  17.             return -1;
  18.         }
  19.        
  20.         int left = _longestZigZag(root->left, false);
  21.         int right = _longestZigZag(root->right, true);
  22.        
  23.         ans = max(ans, 1 + max(left, right));
  24.         return (dir ? left : right) + 1;
  25.     }
  26.    
  27.     int longestZigZag(TreeNode* root) {
  28.         ans = 0;
  29.         _longestZigZag(root, false);
  30.         return ans;
  31.     }
  32. };
RAW Paste Data