From 4838f221f3e01d6a3b8e2a4199283533746ac3fd Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 7 Sep 2022 13:24:41 +0200 Subject: [PATCH] =?UTF-8?q?problems(kt):=20add=20=E2=80=9E606.=20Construct?= =?UTF-8?q?=20String=20from=20Binary=20Tree=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/construct-string-from-binary-tree.kt | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 problems/construct-string-from-binary-tree.kt diff --git a/problems/construct-string-from-binary-tree.kt b/problems/construct-string-from-binary-tree.kt new file mode 100644 index 0000000..60669c4 --- /dev/null +++ b/problems/construct-string-from-binary-tree.kt @@ -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" + } +}