LeetCode 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)".
Example 2:
Input: Binary tree: [1,2,3,null,4]
1
/ \
2 3
\
4 Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example,
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
题解:
类似Binary Tree Preorder Traversal.
Method 1时recursion方法. 但要注意几种特殊情况:
在left child, right child 都是null的情况下是不iterate child 的

如果left child 和right child 中至少有一个不是null 就iterate child 此时无论left child 是否为null 都需要 iterate

在右侧child 不为null时才iterate.

Time Complexity: O(n). 每个节点走了一遍. Space: O(logn), stack space.
AC Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public String tree2str(TreeNode t) {
StringBuilder sb = new StringBuilder();
preorderTraversal(t, sb);
return sb.toString();
} private void preorderTraversal(TreeNode t, StringBuilder sb){
if(t == null){
return;
} sb.append(t.val);
if(t.left == null && t.right == null){
return;
} // 到此说明左右child至少有一个不是null 那么就要iterate left child
sb.append("(");
preorderTraversal(t.left, sb);
sb.append(")"); // right child在不是null时才会iterate
if(t.right != null){
sb.append("(");
preorderTraversal(t.right, sb);
sb.append(")");
}
}
}
Method 2是iteration方法. 类似Binary Tree Preorder Traversal的method 2.
多了visited 来标记已经iterate的点. 在peek stack后如果iterate过了就pop stack 并把")"加到结果中.
Time Complexity: O(n). n是节点个数. Space: O(n).
AC Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public String tree2str(TreeNode t) {
StringBuilder sb = new StringBuilder();
if(t == null){
return sb.toString();
} Stack<TreeNode> stk = new Stack<TreeNode>();
stk.push(t);
HashSet<TreeNode> visited = new HashSet<TreeNode>();
while(!stk.isEmpty()){
TreeNode tn = stk.peek();
if(visited.contains(tn)){
stk.pop();
sb.append(")");
}else{
visited.add(tn);
sb.append("(" + tn.val);
if(tn.left==null && tn.right!=null){
sb.append("()");
}
if(tn.right != null){
stk.push(tn.right);
}
if(tn.left != null){
stk.push(tn.left);
}
}
}
return sb.toString().substring(1,sb.length()-1);
}
}
跟上Construct Binary Tree from String.
LeetCode Construct String from Binary Tree的更多相关文章
- [LeetCode] Construct String from Binary Tree 根据二叉树创建字符串
You need to construct a string consists of parenthesis and integers from a binary tree with the preo ...
- 606. Construct String from Binary Tree 【easy】
606. Construct String from Binary Tree [easy] You need to construct a string consists of parenthesis ...
- 【Leetcode_easy】606. Construct String from Binary Tree
problem 606. Construct String from Binary Tree 参考 1. Leetcode_easy_606. Construct String from Binary ...
- LeetCode 606. Construct String from Binary Tree (建立一个二叉树的string)
You need to construct a string consists of parenthesis and integers from a binary tree with the preo ...
- 【LeetCode】606. Construct String from Binary Tree 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:先序遍历 日期 题目地址:https://l ...
- LeetCode算法题-Construct String from Binary Tree(Java实现)
这是悦乐书的第273次更新,第288篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第141题(顺位题号是606).构造一个字符串,该字符串由二叉树中的括号和整数组成,并具 ...
- LeetCode 606 Construct String from Binary Tree 解题报告
题目要求 You need to construct a string consists of parenthesis and integers from a binary tree with the ...
- [LeetCode&Python] Problem 606. Construct String from Binary Tree
You need to construct a string consists of parenthesis and integers from a binary tree with the preo ...
- LeetCode 606. Construct String from Binary Tree根据二叉树创建字符串 (C++)
题目: You need to construct a string consists of parenthesis and integers from a binary tree with the ...
随机推荐
- 前端之 Ajax(补)
概述 对于WEB应用程序:用户浏览器发送请求,服务器接收并处理请求,然后返回结果,往往返回就是字符串(HTML),浏览器将字符串(HTML)渲染并显示浏览器上. 1.传统的Web应用 一个简单操作需要 ...
- AJAX实现三级联动
省市区三级联动插件: 主页面:为方便使用,不用写过多代码,只写一个id为sanji的div,若别的页面要用,只需写一个id为sanji的div,加载上jQuery与sanji.js文件即可 <! ...
- 13.常见模块re-正则模块
1.正则 正则表达式是计算机科学的一个概念,正则表通常被用来检索.替换那些符合某个模式(规则)的文本.也就是说使用正则表达式可以在字符串中匹配出你需要的字符或者字符串,甚至可以替换你不需要的字符或者字 ...
- Pandas标记删除重复记录
Pandas提供了duplicated.Index.duplicated.drop_duplicates函数来标记及删除重复记录 duplicated函数用于标记Series中的值.DataFrame ...
- 深入理解Node.js中的垃圾回收和内存泄漏的捕获
深入理解Node.js中的垃圾回收和内存泄漏的捕获 文章来自:http://wwsun.github.io/posts/understanding-nodejs-gc.html Jan 5, 2016 ...
- MongoDB快速入门(九)- 投影
MongoDB投影 mongodb投影意义是只选择需要的数据,而不是选择整个一个文档的数据.如果一个文档有5个字段,只需要显示3个,只从中选择3个字段. MongoDB的find()方法,解释了Mon ...
- CentOS 7 安装 maven
下载地址 http://maven.apache.org/download.cgi 版本 apache-maven-3.3.9 -bin.tar.gz tar -xvf apache-maven-3. ...
- alibaba的JSON.toString会把值为null的字段去掉,谨记
alibaba的JSON.toString会把值为null的字段去掉,谨记 Map<String,Object> map = new HashMap<>(); map.put( ...
- PostgreSQL的日志文件介绍
PostgreSQL的日志文件 pg_log:数据库活动日志(也就是数据库的操作日志): pg_xlog:事务日志: pg_clog:事务状态日志(pg_clog是pg_xlog的辅助日志). 现在主 ...
- 本地的html服务
本地的调试的时候, 我们服务器返回的cookie就会变的失效,因为你的本地服务器的域名不太对.