Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
1580923067 opened this issue Aug 8, 2020 · 1 comment

Comments

@1580923067
Copy link

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

@relish-wang
Copy link

relish-wang commented Mar 27, 2024

作者应该是认为每一层都会比上一层多一倍, 没考虑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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants