题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
题目其实很简单,就不说了,但kt的二维数组有点坑。贴个给大家参考吧
object Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param root TreeNode类 * @return int整型二维数组 */ fun levelOrder(root: TreeNode?): Array<IntArray> { if(root == null) { return emptyArray() } val result = ArrayList<IntArray>() var list = ArrayList<TreeNode>() // 做题注意要 import java.util list.add(root) while (list.size > 0) { val curArray = IntArray(list.size) // 每层节点个数刚好等于队列长度 val nextList = ArrayList<TreeNode>() // 下一层的节点列表 // 遍历当前层 for (i in 0 until list.size) { curArray[i] = list[i].`val` list[i].left?.let { nextList.add(it) } list[i].right?.let { nextList.add(it) } } result.add(curArray) list = nextList } // kt 数组可读性太差了 val res = Array(result.size){IntArray(0)} for (i in 0 until res.size) { res[i] = result[i] } result.clear() return res } }