版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanglikun7342/article/details/79051867
问题:
You need to find the largest value in each row of a binary tree.Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
方法:
递归实现,遍历所有节点,递归时传递层级,利用map在同一层级保存最大的数值,最后输出map中的value即为题目所求。
具体实现:
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, ")
}
}
有问题随时沟通