1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00
LeetCode/problems/kt/construct-string-from-binary-tree.kt
Matej Focko 333866d1bc
chore: split solutions by language
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-06-02 17:19:02 +02:00

30 lines
665 B
Kotlin

/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun tree2str(root: TreeNode?): String {
if (root == null) {
return ""
}
val value = root.`val`.toString()
val left = "(${tree2str(root.left)})"
val right = "(${tree2str(root.right)})"
if (left == "()" && right == "()") {
return value
} else if (right == "()") {
return "$value$left"
}
return "$value$left$right"
}
}