树的打印函数好像对null处理有点问题,麻烦大佬帮看下
1580923067 opened this issue · 1 comments
1580923067 commented
例如Leetcode94题,输入: [1,null,2,3],调用TreeNode.print( )函数,3会丢失
relish-wang commented
作者应该是认为每一层都会比上一层多一倍, 没考虑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
}