606. Construct String from Binary Tree

复制代码
package LeetCode_606

import LeetCode_1382.TreeNode

/**
 * 606. Construct String from Binary Tree
 * https://leetcode.com/problems/construct-string-from-binary-tree/description/
 * You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()".
And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship
between the string and the original binary tree.
Example 1:
Input: Binary tree: [1,2,3,4]
     1
   /   \
  2     3
 /
4
Output: "1(2(4))(3)"
Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)".
 * */
class Solution {
    /*
    * Time complexity:O(n), Space complexity:O(logn)
    * */
    fun tree2str(t: TreeNode?): String {
        if (t == null) {
            return ""
        }
        //pre-order mode: root->left->right
        val s = t.`val`.toString()
        val l = tree2str(t.left)
        val r = tree2str(t.right)

        if (t.left == null && t.right == null) {
            return s
        }
        if (t.right == null) {
            return s + "($l)"
        }
        return s + "($l)($r)"
    }
}
复制代码

 

posted @   johnny_zhao  阅读(55)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示