美文网首页
LeetCode之Binary Tree Level Order

LeetCode之Binary Tree Level Order

作者: 糕冷羊 | 来源:发表于2021-10-25 20:58 被阅读0次

问题:



方法:
递归遍历,然后按深度存入不同的list,最后输出map的values即为不同层级的nodes。

package com.eric.leetcode

class BinaryTreeLevelOrderTraversalII {
    private val result = mutableMapOf<Int, MutableList<Int>>()
    fun levelOrderBottom(root: TreeNode?): List<List<Int>> {
        result.clear()
        root?.let { search(it, 0) }
        return result.values.reversed()
    }

    private fun search(root: TreeNode, depth: Int) {
        val list = result[depth]
        if (list == null) {
            result[depth] = mutableListOf(root.`val`)
        } else {
            list.add(root.`val`)
        }
        root.left?.let {
            search(it, depth + 1)
        }
        root.right?.let {
            search(it, depth + 1)
        }
    }
}

有问题随时沟通

具体代码实现可以参考Github

相关文章

网友评论

      本文标题:LeetCode之Binary Tree Level Order

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