2583. 二叉树中的第 K 大层和

二叉树中的第 K 大层和

解法一: 广度优先遍历

go
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
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func kthLargestLevelSum(root *TreeNode, k int) int64 {
queue := []*TreeNode{root}
var sumArr []int64
for len(queue) > 0 {
size := len(queue)
var sum int64
for i := 0; i < size; i++ {
node := queue[i]
sum += int64(node.Val)
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
queue = queue[size:]
sumArr = append(sumArr, sum)
}
if len(sumArr) < k {
return -1
}
sort.Slice(sumArr, func(i, j int) bool {
return sumArr[i] >= sumArr[j]
})
return sumArr[k-1]
}

解法二: 深度优先遍历

Go
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
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func kthLargestLevelSum(root *TreeNode, k int) int64 {
var sumArr []int64
var dfs func(*TreeNode, int)
dfs = func(node *TreeNode, depth int) {
if node == nil {
return
}
if len(sumArr) <= depth {
sumArr = append(sumArr, 0)
}
sumArr[depth] += int64(node.Val)
dfs(node.Left, depth+1)
dfs(node.Right, depth+1)
}
dfs(root, 0)
if len(sumArr) < k {
return -1
}
sort.Slice(sumArr, func(i, j int) bool {
return sumArr[i] >= sumArr[j]
})
return sumArr[k-1]
}
作者

wuhunyu

发布于

2024-02-23

更新于

2025-01-15

许可协议