题目
给你一棵二叉树的根节点,返回该树的 直径 。
二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。
两节点之间路径的 长度 由它们之间边数表示。
示例 1:
输入:root = \[1,2,3,4,5]
输出:3
解释:3 ,取路径 \[4,2,1,3] 或 \[5,2,1,3] 的长度。
示例 2:
输入:root = \[1,2]
输出:1
思路
本题采用递归的方式实现。具体思路是:对于一个节点,以该节点为根节点,求出左右子树的深度和距离;在遍历完所有节点后,选取最长的距离作为答案即可。
代码如下:
function diameterOfBinaryTree(root: TreeNode | null): number {
let res = 0
if (!root) return res
const depth = (node: TreeNode | null): number => {
if (!node) return 0
const leftDepth = depth(node.left)
const rightDepth = depth(node.right)
res = Math.max(res, leftDepth + rightDepth)
return Math.max(leftDepth, rightDepth) + 1
}
depth(root)
return res
}
复杂度分析:
-
时间复杂度:O(n),其中 n 是二叉树中的节点数。在最坏情况下,需要遍历二叉树中的所有节点,因此时间复杂度为 O(n)。
-
空间复杂度:O(n),空间复杂度取决于递归的深度,而在最坏情况下,二叉树退化成链状结构,因此递归深度最大为 n,空间复杂度为 O(n)。