原题链接:https://leetcode-cn.com/problems/longest-zigzag-path-in-a-binary-tree/
嵌套递归(超时)
相关题目:二叉树中的列表
int longestZigZag(TreeNode* root) {
if(root==NULL) return 0;
return max(max(ZigZag(root,true),ZigZag(root,false))-1,max(longestZigZag(root->left),longestZigZag(root->right)));
}
int ZigZag(TreeNode *root,bool left){
if(root==NULL) return 0;
if(left){
return ZigZag(root->left,false)+1;
}else{
return ZigZag(root->right,true)+1;
}
}
这种方法的问题在于执行max(longestZigZag(root->left),longestZigZag(root->right))
时,会存在重复计算,优化方法是将路径长度作为参数传入,如果符合z字交错,则将路径长度加1,不符合时,将路径长度置1,这样时间复杂度只有O(n),也是一种动态规划的思路。
int longestZigZag(TreeNode* root) {
int ans=0;
return max(ZigZag(root,true,ans),ZigZag(root,false,ans))-1;
}
int ZigZag(TreeNode *root,bool left,int ans){//满足z字交错时,将路径长度加1,不满足时,将路径长度置1
if(root==NULL) return ans;
if(left){
return max(ZigZag(root->left,false,ans+1),ZigZag(root->right,true,1));
}else{
return max(ZigZag(root->left,false,1),ZigZag(root->right,true,ans+1));
}
}