题目:

代码(首刷看解析):
class Solution {
public:
    int maxAns;
    //dir 0 left,1 right
    void dfs(TreeNode* root,bool dir,int len){
        maxAns=max(maxAns,len);
        if(!dir){
            if(root->left)  dfs(root->left,1,len+1);
            if(root->right) dfs(root->right,0,1);
        }else{
            if(root->right) dfs(root->right,0,len+1);
            if(root->left)  dfs(root->left,1,1);
        }
    }
    int longestZigZag(TreeNode* root) {
        if(!root) return 0;
        maxAns = 0;
        dfs(root,0,0);
        dfs(root,1,0);
        return maxAns;
    }
};


















