二叉树的直径

GitHub跳转原题关系图返回列表

后序返回高度,经过当前点的候选为 left+right,全局取最大。

OJ: leetcodecn

题目 ID: diameter-of-binary-tree

难度:入门

标签:二叉树递归树形DPcpppython

日期: 2026-07-28 22:05

题意

二叉树直径 = 任意两节点间最长路径的边数。

思路

对每个节点,经过它的最长路径 = 左子树最大深度 + 右子树最大深度。DFS 后序返回子树深度,同时全局更新答案。

代码

cpp
/**
 * Author by Rainboy
 */
#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left, *right;

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
    int diameterOfBinaryTree(TreeNode *root) {
        int ans = 0;
        function<int(TreeNode *)> dfs = [&](TreeNode *r) {
            if (!r)
                return 0;
            int l = dfs(r->left), rdep = dfs(r->right);
            ans = max(ans, l + rdep);
            return 1 + max(l, rdep);
        };
        dfs(root);
        return ans;
    }
};

TreeNode *build(istream &in, int n) {
    if (!n)
        return nullptr;
    vector<TreeNode *> nodes(n);
    for (int i = 0, v; i < n; i++) {
        in >> v;
        if (v != -1)
            nodes[i] = new TreeNode(v);
    }
    queue<TreeNode *> q;
    TreeNode *root = nodes[0];
    if (root)
        q.push(root);
    int idx = 1;
    while (!q.empty() && idx < n) {
        auto cur = q.front();
        q.pop();
        if (idx < n) {
            cur->left = nodes[idx];
            if (nodes[idx])
                q.push(nodes[idx]);
            idx++;
        }
        if (idx < n) {
            cur->right = nodes[idx];
            if (nodes[idx])
                q.push(nodes[idx]);
            idx++;
        }
    }
    return root;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    auto root = build(cin, n);
    cout << Solution().diameterOfBinaryTree(root) << '\n';
    return 0;
}
python
#!/usr/bin/env python3
from collections import deque
from typing import Optional


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        ans = 0

        def dfs(r):
            nonlocal ans
            if not r:
                return 0
            l = dfs(r.left)
            rd = dfs(r.right)
            ans = max(ans, l + rd)
            return 1 + max(l, rd)

        dfs(root)
        return ans


def build(arr):
    if not arr:
        return None
    nodes = [TreeNode(v) if v != -1 else None for v in arr]
    q = deque([nodes[0]]) if nodes[0] else deque()
    idx = 1
    while q and idx < len(arr):
        cur = q.popleft()
        if idx < len(arr):
            cur.left = nodes[idx]
            if nodes[idx]:
                q.append(nodes[idx])
            idx += 1
        if idx < len(arr):
            cur.right = nodes[idx]
            if nodes[idx]:
                q.append(nodes[idx])
            idx += 1
    return nodes[0]


def main() -> None:
    n = int(input())
    a = list(map(int, input().split()))
    root = build(a)
    print(Solution().diameterOfBinaryTree(root))


if __name__ == "__main__":
    main()

复杂度

  • 时间复杂度:O(n)。
  • 空间复杂度:O(height)。

总结

"后序返回单侧值、全局更新跨双侧答案"是树形 DP 的基础模式,二叉树的直径和最大路径和都沿用此模型。