题目描述
🔥 543. 二叉树的直径
思路分析
对于每一个节点,它的直径长度为左子树的最大深度加上右子树的最大深度。因此,我们可以递归地求出每一个节点的左右子树的最大深度,然后计算直径长度。
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| func diameterOfBinaryTree(root *TreeNode) int {
if root == nil {
return 0
}
// 定义一个全局变量来保存最大直径
var maxDiameter int
dfs(root, &maxDiameter)
return maxDiameter
}
func dfs(node *TreeNode, maxDiameter *int) int {
if node == nil {
return 0
}
// 递归计算左子树和右子树的深度
leftDepth := dfs(node.Left, maxDiameter)
rightDepth := dfs(node.Right, maxDiameter)
// 更新最大直径
*maxDiameter = max(*maxDiameter, leftDepth+rightDepth)
// 返回当前子树的深度
return max(leftDepth, rightDepth) + 1
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| func diameterOfBinaryTree(root *TreeNode) int {
if root == nil {
return 0
}
queue := []*TreeNode{root}
maxDiameter := 0
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
leftDepth := maxDepth(node.Left)
rightDepth := maxDepth(node.Right)
// 更新全局最大直径
if leftDepth+rightDepth > maxDiameter {
maxDiameter = leftDepth + rightDepth
}
// 将左右子节点加入队列
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
return maxDiameter
}
func maxDepth(node *TreeNode) int {
if node == nil {
return 0
}
leftDepth := maxDepth(node.Left)
rightDepth := maxDepth(node.Right)
if leftDepth > rightDepth {
return leftDepth + 1
}
return rightDepth + 1
}
|
🍏 点击查看 Java 题解
版权声明:
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!