Blankj/awesome-java-leetcode

树的打印函数好像对null处理有点问题,麻烦大佬帮看下

1580923067 opened this issue · 1 comments

例如Leetcode94题,输入: [1,null,2,3],调用TreeNode.print( )函数,3会丢失

作者应该是认为每一层都会比上一层多一倍, 没考虑null的情况,导致createTestData方法生成的TreeNode对象错误, 用双队列处理即可(有点像bfs), 我把createTestData方法修正了一下, 不过改成kotlin了。

fun createTestData(str: String): TreeNode? {
    var data = str
    if (data == "[]") return null
    data = data.substring(1, data.length - 1)
    val split = data.split(",")
    val len = split.size
    val qLow = LinkedList<Int?>()
    for (i in split.indices) {
        split[i].let {
            qLow.offer(
                if (it == "null") {
                    null
                } else {
                    it.toInt()
                }
            )
        }
    }
    val qHigh = LinkedList<TreeNode?>()
    if (qLow.isEmpty()) {
        return null
    }
    val rv = qLow.poll() ?: return null
    val root = TreeNode(rv)
    qHigh.offer(root)
    while (qHigh.isNotEmpty()) {
        val r = qHigh.poll() ?: continue
        val left = (qLow.poll()?.let { TreeNode(it) }).also { qHigh.offer(it) }
        val right = (qLow.poll()?.let { TreeNode(it) }).also { qHigh.offer(it) }
        r.left = left
        r.right = right
    }
    return root
}