top1编程
← 返回题目
题解

【深基16.例3】二叉树深度

1 条题解

  • 0
    @ 2026-10-21 0:58:56

    1. 解题思路

    用队列从根1遍历,队列元素保存结点编号与深度;将非空子结点以深度加1入队,取最大深度。

    2. 坑点和注意事项

    n≤10^6。根深度为1,子结点0表示不存在;采用迭代避免退化链导致递归栈溢出。

    3. 复杂度

    • 时间复杂度:O(n)。
    • 空间复杂度:O(n)。
    /*
    思路:用队列从根1遍历,队列元素保存结点编号与深度;将非空子结点以深度加1入队,取最大深度。
    关键规则与坑点:n≤10^6。根深度为1,子结点0表示不存在;采用迭代避免退化链导致递归栈溢出。
    时间复杂度:O(n)。空间复杂度:O(n)。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int l[1000005], r[1000005];
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> l[i] >> r[i];
        queue<pair<int, int>> q;
        q.push({1, 1});
        int ans = 0;
        while (!q.empty())
        {
            int v = q.front().first, d = q.front().second;
            q.pop();
            ans = max(ans, d);
            if (l[v])
                q.push({l[v], d + 1});
            if (r[v])
                q.push({r[v], d + 1});
        }
        cout << ans << endl;
    }
    
    • 1