-
Difficulty: Easy
-
Related Topics: Tree
-
Link: https://leetcode.com/problems/diameter-of-binary-tree/
Description
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
给定一棵二叉树,你需要计算二叉树直径的长度。二叉树的直径是二叉树内任意两节点间路径的最大值。这个路径不一定经过二叉树的根。
Examples
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note
The length of path between two nodes is represented by the number of edges between them.
两节点间路径的长度以两节点间经过的边的数量表示。
Solution
题目里明说了,二叉树的直径不一定经过 root
。二叉树的直径有可能在以下地方出现:
-
完全位于左子树
-
完全位于右子树
-
经过
root
(即跨越了左右子树)
前两种情况比较好处理,递归求解问题即可,需要注意的是第 3 种情况。由于情况 3 要考虑跨越左右子树的情况,所以对左右子问题的求解结果应该只是当直径不跨越 root
的情况(直径若在这之前跨越了子树的 root
,父问题就无法求解了),于是需要把最后的结果单独拿出来处理,最后得到如下解答。
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `va`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
import kotlin.math.max
class Solution {
private var result = 0
fun diameterOfBinaryTree(root: TreeNode?): Int {
dfs(root)
return result
}
private fun dfs(root: TreeNode?): Int {
if (root == null) {
return 0
}
val leftResult = dfs(root.left)
val rightResult = dfs(root.right)
// 在这里处理直径跨越 `root` 的情况
result = max(result, leftResult + rightResult)
// 递归返回时只返回不跨越 `root` 的情况
return max(leftResult, rightResult) + 1
}
}