美文网首页
LeetCode之Find Largest Value in E

LeetCode之Find Largest Value in E

作者: 糕冷羊 | 来源:发表于2019-01-01 00:09 被阅读0次

问题:
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, ")
    }
}

有问题随时沟通

具体代码实现可以参考Github

相关文章

网友评论

      本文标题:LeetCode之Find Largest Value in E

      本文链接:https://www.haomeiwen.com/subject/fwuglqtx.html