LeetCode之Find Largest Value in Each Tree Row(Kotlin)

問題: 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

具體代碼實現能夠參考Githubspa

相關文章
相關標籤/搜索