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 {
- public:
- int ans=0;
- unordered_map<TreeNode*,int> m;
- int maxZigZag(TreeNode* root,int dir){
- if(root==nullptr){
- return 0;
- }
- if(dir==1){
- return 1+maxZigZag(root->left,0);
- }else{
- return 1+maxZigZag(root->right,1);
- }
- }
- void dfs(TreeNode* root){
- if(root==nullptr){
- return;
- }
- int a=0;
- if(m[root]==0){
- a=max(maxZigZag(root->left,0),maxZigZag(root->right,1));
- m[root]=a;
- }else{
- a=m[root];
- }
- ans=max(ans,a);
- dfs(root->right);
- dfs(root->left);
- return;
- }
- int longestZigZag(TreeNode* root) {
- dfs(root);
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement