Given a binary tree, compute the diameter of the tree.
The diameter is the longest path between any two nodes in the tree.
这道题要求计算二叉树的直径,也就是树中任意两点之间最长路径的长度。典型做法是用深度优先搜索(DFS)自底向上遍历每个节点:对每个节点分别计算左子树和右子树的最大深度,并用“左深度 + 右深度”更新全局答案,因为经过该节点的最长路径一定由两边最深分支组成。实现时通常只需要一次递归遍历,时间复杂度为 O(n),空间复杂度为递归栈深度 O(h)。
正文完