题解 | #序列化二叉树#
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
kotlin
前序遍历
/**
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
object Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param root TreeNode类
* @return TreeNode类
*/
var index = 0
val stringBuilder = StringBuilder()
fun Serialize(root: TreeNode?): String {
if(root == null) return ""
dfs(root)
//删除最后多余的逗号
stringBuilder.deleteCharAt(stringBuilder.length - 1)
return stringBuilder.toString()
}
private fun dfs(root: TreeNode?) {
//子树为空是递归返回点
if(root == null) {
stringBuilder.append("#,")
return
}
//加逗号分割符
stringBuilder.append(root.`val`).append(",")
dfs(root.left)
dfs(root.right)
}
fun Deserialize(str: String): TreeNode? {
if(str == "") return null
val array = str.split(",")
return buildTree(array)
}
private fun buildTree(array: List<String>): TreeNode? {
if(index >= array.size || array[index] == "#") {
index++
return null
}
val root = TreeNode(array[index++].toInt())
val left = buildTree(array)
val right = buildTree(array)
root.left = left
root.right = right
return root
}
}
