leetcode地址:层数最深叶子节点的和
给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。
示例 1:
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15
示例 2:
输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
输出:19
提示:
树中节点数目在范围 [1, 104] 之间。
1 <= Node.val <= 100
实现思路
广度优先搜索(BFS):
使用队列进行层次遍历,逐层扫描树。
每次进入新的一层时,重置当前层的和。
记录当前层的叶子节点和,直到遍历完整棵树。
深度优先搜索(DFS):
使用递归方法,记录每个节点的层数。
通过递归遍历树,更新当前层数和最深层叶子节点和。
返回最深层叶子节点和。
代码详解
广度优先搜索(BFS)
使用广度优先搜索(BFS)遍历树,每次进入新的一层时,重置当前层的和,并累加当前层的叶子节点值,直到遍历完整棵树。
from collections import deque
# 定义二叉树节点类
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# BFS方法返回层数最深的叶子节点的和
def deepestLeavesSumBFS(root):
if not root:
return 0
queue = deque([root])
while queue:
level_sum = 0
for _ in range(len(queue)):
node = queue.popleft()
level_sum += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return level_sum
# 测试示例
if __name__ == "__main__":
# 创建测试二叉树
# 1
# / \
# 2 3
# / \ \
# 4 5 6
# / / \
# 7 8 9
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.right = TreeNode(6)
root.left.left.left = TreeNode(7)
root.right.right.left = TreeNode(8)
root.right.right.right = TreeNode(9)
result = deepestLeavesSumBFS(root)
print("层数最深的叶子节点的和 (BFS):", result) # 应该输出24
深度优先搜索(DFS)
使用深度优先搜索(DFS)遍历树,记录每个节点的层数。通过递归遍历树,更新当前层数和最深层叶子节点和。
# 定义二叉树节点类
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# DFS方法返回层数最深的叶子节点的和
def deepestLeavesSumDFS(root):
if not root:
return 0
max_depth = -1
sum_at_max_depth = 0
def dfs(node, depth):
nonlocal max_depth, sum_at_max_depth
if not node:
return
# 如果是叶子节点
if not node.left and not node.right:
if depth > max_depth:
max_depth = depth
sum_at_max_depth = node.val
elif depth == max_depth:
sum_at_max_depth += node.val
else:
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
dfs(root, 0)
return sum_at_max_depth
# 测试示例
if __name__ == "__main__":
# 创建测试二叉树
# 1
# / \
# 2 3
# / \ \
# 4 5 6
# / / \
# 7 8 9
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.right = TreeNode(6)
root.left.left.left = TreeNode(7)
root.right.right.left = TreeNode(8)
root.right.right.right = TreeNode(9)
result = deepestLeavesSumDFS(root)
print("层数最深的叶子节点的和 (DFS):", result) # 应该输出24
go实现
广度优先搜索(BFS)
package main
import (
"fmt"
)
// TreeNode 定义二叉树节点
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// deepestLeavesSumBFS 使用广度优先搜索(BFS)返回层数最深的叶子节点的和
func deepestLeavesSumBFS(root *TreeNode) int {
if root == nil {
return 0
}
queue := []*TreeNode{root}
var levelSum int
for len(queue) > 0 {
levelSum = 0
qLen := len(queue)
for i := 0; i < qLen; i++ {
node := queue[0]
queue = queue[1:]
levelSum += node.Val
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
}
return levelSum
}
// 测试示例
func main() {
// 创建测试二叉树
// 1
// / \
// 2 3
// / \ \
// 4 5 6
// / / \
// 7 8 9
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 3}
root.Left.Left = &TreeNode{Val: 4}
root.Left.Right = &TreeNode{Val: 5}
root.Right.Right = &TreeNode{Val: 6}
root.Left.Left.Left = &TreeNode{Val: 7}
root.Right.Right.Left = &TreeNode{Val: 8}
root.Right.Right.Right = &TreeNode{Val: 9}
result := deepestLeavesSumBFS(root)
fmt.Printf("层数最深的叶子节点的和 (BFS): %d\n", result) // 应该输出24
}
深度优先搜索(DFS)
package main
import (
"fmt"
)
// TreeNode 定义二叉树节点
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// deepestLeavesSumDFS 使用深度优先搜索(DFS)返回层数最深的叶子节点的和
func deepestLeavesSumDFS(root *TreeNode) int {
if root == nil {
return 0
}
var maxDepth int
var sumAtMaxDepth int
var dfs func(node *TreeNode, depth int)
dfs = func(node *TreeNode, depth int) {
if node == nil {
return
}
// 如果是叶子节点
if node.Left == nil && node.Right == nil {
if depth > maxDepth {
maxDepth = depth
sumAtMaxDepth = node.Val
} else if depth == maxDepth {
sumAtMaxDepth += node.Val
}
} else {
dfs(node.Left, depth+1)
dfs(node.Right, depth+1)
}
}
dfs(root, 0)
return sumAtMaxDepth
}
// 测试示例
func main() {
// 创建测试二叉树
// 1
// / \
// 2 3
// / \ \
// 4 5 6
// / / \
// 7 8 9
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 3}
root.Left.Left = &TreeNode{Val: 4}
root.Left.Right = &TreeNode{Val: 5}
root.Right.Right = &TreeNode{Val: 6}
root.Left.Left.Left = &TreeNode{Val: 7}
root.Right.Right.Left = &TreeNode{Val: 8}
root.Right.Right.Right = &TreeNode{Val: 9}
result := deepestLeavesSumDFS(root)
fmt.Printf("层数最深的叶子节点的和 (DFS): %d\n", result) // 应该输出24
}
Kotlin实现
广度优先搜索(BFS)
import java.util.LinkedList
import java.util.Queue
// 定义二叉树节点类
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
// BFS方法返回层数最深的叶子节点的和
fun deepestLeavesSumBFS(root: TreeNode?): Int {
if (root == null) return 0
var sum = 0
val queue: Queue<TreeNode> = LinkedList()
queue.add(root)
// 广度优先搜索(BFS)
while (queue.isNotEmpty()) {
sum = 0 // 重置当前层的和
val size = queue.size
for (i in 0 until size) {
val node = queue.poll()
sum += node.`val` // 累加当前层节点的值
// 将左右子节点加入队列
node.left?.let { queue.add(it) }
node.right?.let { queue.add(it) }
}
}
return sum
}
// 测试示例
fun main() {
// 创建测试二叉树
// 1
// / \
// 2 3
// / \ \
// 4 5 6
// / / \
// 7 8 9
val root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left?.left = TreeNode(4)
root.left?.right = TreeNode(5)
root.right?.right = TreeNode(6)
root.left?.left?.left = TreeNode(7)
root.right?.right?.left = TreeNode(8)
root.right?.right?.right = TreeNode(9)
val result = deepestLeavesSumBFS(root)
println("层数最深的叶子节点的和 (BFS): $result") // 应该输出24
}
深度优先搜索(DFS)
// 定义二叉树节点类
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
// DFS方法返回层数最深的叶子节点的和
fun deepestLeavesSumDFS(root: TreeNode?): Int {
if (root == null) return 0
var maxDepth = -1
var sumAtMaxDepth = 0
fun dfs(node: TreeNode?, depth: Int) {
if (node == null) return
// 如果是叶子节点
if (node.left == null && node.right == null) {
if (depth > maxDepth) {
maxDepth = depth
sumAtMaxDepth = node.`val`
} else if (depth == maxDepth) {
sumAtMaxDepth += node.`val`
}
} else {
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
}
}
dfs(root, 0)
return sumAtMaxDepth
}
// 测试示例
fun main() {
// 创建测试二叉树
// 1
// / \
// 2 3
// / \ \
// 4 5 6
// / / \
// 7 8 9
val root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left?.left = TreeNode(4)
root.left?.right = TreeNode(5)
root.right?.right = TreeNode(6)
root.left?.left?.left = TreeNode(7)
root.right?.right?.left = TreeNode(8)
root.right?.right?.right = TreeNode(9)
val result = deepestLeavesSumDFS(root)
println("层数最深的叶子节点的和 (DFS): $result") // 应该输出24
}