问题: You need to find the largest value in each row of a binary tree.git
Input: 复制代码
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
复制代码
方法: 递归实现,遍历全部节点,递归时传递层级,利用map在同一层级保存最大的数值,最后输出map中的value即为题目所求。github
具体实现:bash
class FindLargestValueInEachTreeRow {
private val mutableMap = mutableMapOf<Int, Int>()
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun largestValues(root: TreeNode?): List<Int> {
findValues(root, 1)
return mutableMap.values.toList()
}
private fun findValues(root: TreeNode?, level: Int) {
if (root == null) {
return
}
val value = mutableMap[level]
if (value == null || value < root.`val`) {
mutableMap.put(level, root.`val`)
}
findValues(root.left, level + 1)
findValues(root.right, level + 1)
}
}
fun main(args: Array<String>) {
val root = FindLargestValueInEachTreeRow.TreeNode(5)
root.left = FindLargestValueInEachTreeRow.TreeNode(3)
root.right = FindLargestValueInEachTreeRow.TreeNode(6)
(root.left)?.left = FindLargestValueInEachTreeRow.TreeNode(2)
(root.left)?.right = FindLargestValueInEachTreeRow.TreeNode(4)
(root.right)?.right = FindLargestValueInEachTreeRow.TreeNode(7)
val findLargestValueInEachTreeRow = FindLargestValueInEachTreeRow()
val result = findLargestValueInEachTreeRow.largestValues(root)
for (e in result) {
print("$e, ")
}
}
复制代码
有问题随时沟通ui