领扣LintCode算法问题答案-1137. 从二叉树构建字符串
发布日期:2021-06-30 17:09:58 浏览次数:2 分类:技术文章

本文共 1362 字,大约阅读时间需要 4 分钟。

领扣LintCode算法问题答案-1137. 从二叉树构建字符串

目录

1137. 从二叉树构建字符串

描述

你需要通过一棵二叉树的先序遍历,构建一个包含括号和整数的字符串。

空结点需要用空括号对"()"来表示。同时你需要忽略掉所有的不影响字符串和原始二叉树一对一映射关系的空括号对。

样例 1:

输入: Binary tree: [1,2,3,4]       1     /   \    2     3   /      4     输出: "1(2(4))(3)"解释: 一开始应该是 "1(2(4)())(3()())", 但是你需要忽略掉所有的不必要的空括号对. 然后就变成了 "1(2(4))(3)".

样例 2:

输入: Binary tree: [1,2,3,null,4]       1     /   \    2     3     \        4 输出: "1(2()(4))(3)"解释: 几乎和第一个样例相同, 除了我们不能忽略第一个括号对,否则将会破坏输入和输出之间的一对一映射关系。

题解

/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {
/** * @param t: the root of tree * @return: return a string */ public String tree2str(TreeNode t) {
// write your code here if (t == null) {
return ""; } String str = String.valueOf(t.val); str += "(" + tree2str(t.left) + ")"; str += "(" + tree2str(t.right) + ")"; while (str.contains("())")) {
str = str.replaceAll("\\(\\)\\)", ")"); } while (str.endsWith("()")) {
str = str.substring(0, str.length() - 2); } return str; }}

鸣谢

非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。

欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

转载地址:https://le-yi.blog.csdn.net/article/details/108841756 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1138. 能否放置花
下一篇:领扣LintCode算法问题答案-1133. 团购

发表评论

最新留言

不错!
[***.144.177.141]2024年04月21日 05时57分39秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章