problems(kt): add „606. Construct String from Binary Tree“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
20e3625bd7
commit
4838f221f3
1 changed files with 30 additions and 0 deletions
30
problems/construct-string-from-binary-tree.kt
Normal file
30
problems/construct-string-from-binary-tree.kt
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
/**
|
||||||
|
* 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"
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue