Advertisement
jibha

Untitled

Feb 1st, 2022
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 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. public:
  14. int ans=0;
  15. unordered_map<TreeNode*,int> m;
  16. int maxZigZag(TreeNode* root,int dir){
  17.  
  18. if(root==nullptr){
  19. return 0;
  20. }
  21.  
  22. if(dir==1){
  23.  
  24. return 1+maxZigZag(root->left,0);
  25.  
  26. }else{
  27.  
  28. return 1+maxZigZag(root->right,1);
  29.  
  30. }
  31. }
  32.  
  33.  
  34. void dfs(TreeNode* root){
  35.  
  36. if(root==nullptr){
  37. return;
  38. }
  39. int a=0;
  40. if(m[root]==0){
  41. a=max(maxZigZag(root->left,0),maxZigZag(root->right,1));
  42. m[root]=a;
  43. }else{
  44. a=m[root];
  45. }
  46.  
  47.  
  48. ans=max(ans,a);
  49.  
  50. dfs(root->right);
  51. dfs(root->left);
  52. return;
  53. }
  54.  
  55.  
  56.  
  57. int longestZigZag(TreeNode* root) {
  58.  
  59. dfs(root);
  60.  
  61. return ans;
  62. }
  63. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement