import (
"sort"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func kthLargestLevelSum(root *TreeNode, k int) int64 {
res := make([]int, 0)
if root == nil {
return int64(res[0])
}
//用切片模拟队列存放当前层节点
curList := []*TreeNode{root}
for len(curList) > 0 {
//生成下一层
nextList := []*TreeNode{}
vals := 0
for _, v := range curList {
//计算当前层和
vals += v.Val
if v.Left != nil {
nextList = append(nextList, v.Left)
}
if v.Right != nil {
nextList = append(nextList, v.Right)
}
}
res = append(res, vals)
//将下一层变成当前层
curList = nextList
}
if len(res) < k {
return -1
}
//从大到小排序
sort.Sort(sort.Reverse(sort.IntSlice(res)))
return int64(res[k-1])
}