洛谷 P4913 二叉树深度 / 二叉树 / 求二叉树的最大深度

洛谷 P4913 二叉树深度

这样写若循环到 i 时 i 的父节点还没被更新,则 i 的深度会比实际小
所以不能在线更新
必须全部存储起来,而后离线按逻辑顺序更新(即更新子节点时一定要保证父节点被更新了)

错误代码:

#include <iostream>
#include <algorithm>
using namespace std;

const int N = 1e6 + 10;

int n;
int depth[N];
int ans = 0;
// 这样写若循环到 i 时 i 的父节点还没被更新,则 i 的深度会比实际小
// 所以不能在线更新
// 必须全部存储起来,按逻辑顺序更新(即更新子节点时一定要保证父节点被更新了)
int main()
{
    cin >> n;

    depth[1] = 1;
    for (int i = 1; i <= n; i ++ )
    {
        int le, rig;
        cin >> le >> rig;

        depth[le] = depth[i] + 1;
        depth[rig] = depth[i] + 1;

        ans = max(ans, depth[i]);
    }

    //for (int i = 1; i <= n; i ++ ) cout << depth[i] << ' ';
    //cout << '\n';
    cout << "ans=" << ans;

    return 0;
}
/*
bug 数据
6
6 5
0 0
0 0
0 0
0 3
2 4
*/
posted @ 2023-04-18 09:33  妃即  阅读(26)  评论(0)    收藏  举报