leetcode1372dp求交错路径长

  • bfs+dp
unordered_map<TreeNode* ,int>d,p;
queue<pair<TreeNode* ,TreeNode*>>q;
int dp(TreeNode* root){
    d[root]=p[root]=0;
    q.push({root,nullptr});
    while(!q.empty()){
        auto x=q.front();q.pop();
        auto y=x.second();
        auto u=x.first();
        d[u]=p[u]=0;//因为在经过所有节点时,可能有些d或p值不会被赋值,导致后面遍历找最大值时漏掉
        if(y){
            if(y->left)d[u]=p[y]+1;
            if(y->right)p[u]=d[y]+1;
        }
        if(u->left)q.push(u->left,u);
        if(u->right)q,push(u->right,u);
    }
}
int longestZigZag(TreeNode* root){
    dp(root);
    int maxans=0;
    for(const auto &u:f)maxans=max(maxans,max(u.first,p[u.first]));
    return maxans;
}
  •  bfs
int maxAns=0;
void dfs(TreeNode* root,int count,int direct){
    if(!root)return;
    maxAns=max(maxAns,count);//每走一个节点就要看看交错路径的最长长度
    if(root->left)dfs(root->left,direct==1?1:count+1,1);//向左,要是上一节点也是左,那么交错路长度就要重新计算
    if(root->right)dfs(root->right,direct==2?1:count+1,2);
}
int longestZigZag(TreeNode* root){
    if(!root)return 0;
    dfs(root->left,1,1);//count以1开始,因为只要该子节点不为空,就要更新为1
    dfs(root->right,1,2);
    return maxAns;
}

 

posted @ 2023-08-18 19:11  iu本u  阅读(25)  评论(0)    收藏  举报