原题题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210104221638324.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3NTAwNTE2,size_16,color_FFFFFF,t_70)
代码实现(暴力解法 超时)
int maxpaths;void visit(struct TreeNode* root,int direction,int paths)
{
if(root){
if(paths > maxpaths)maxpaths = paths;if(direction == 1)visit(root->right,0,paths+1);elsevisit(root->left,1,paths+1);}
}void go(struct TreeNode* root)
{
if(root){
visit(root,0,0);visit(root,1,0);go(root->left);go(root->right);}
}int longestZigZag(struct TreeNode* root){
if(!root)return 0;maxpaths = 0;go(root);return maxpaths;
}
代码实现(递归继承法 只遍历一次)
int maxpaths;void visit(struct TreeNode* root,int direction,int paths)
{
if(root){
if(paths > maxpaths)maxpaths = paths;if(!direction){
visit(root->left,1,paths+1);visit(root->right,0,1);}else{
visit(root->left,1,1);visit(root->right,0,paths+1);}}
}int longestZigZag(struct TreeNode* root){
if(!root)return 0;maxpaths = 0;visit(root,0,0); visit(root,1,0);return maxpaths;
}