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 ...
随机推荐
- PHP/Yii2操作Cookie,常见问题以及注意事项
设置Cookie PHP setcookie("name", "Larry",time()+3600 Yii2 $cookies = Yii::$app-> ...
- 每天一个Linux命令(64)shutdown命令
shutdown以一种安全的方式关闭系统. (1)用法: 用法: shutdown [参数] [时间] (2)功能: 功能: 系统关机命令,shutdown ...
- Linux Shell基础 多个命令中的分号(;)、与(&&) 、 或(||)
概述 在 Bash 中,如果需要让多条命令按顺序执行,则有这样方法,如表 1 所示. 多命令执行符 格 式 作 用 : 命令1 ; 命令2 多条命令顺序执行,命令之间没有任何逻辑关系 &&am ...
- 【HackerRank】Ice Cream Parlor
Sunny and Johnny together have M dollars which they intend to use at the ice cream parlour. Among N ...
- 【转载】OPENWRT入门之四------openwrt命令行模式命令及其工具
连接来源http://bbs.xiaomi.cn/thread-9734746-1-1.html 需要学会用ssh登录路由器用linux命令查看.ps 命令查看当前系统运行的进程信息free 命令查看 ...
- python中编写带参数decorator
考察上一节的 @log 装饰器: def log(f): def fn(x): print 'call ' + f.__name__ + '()...' return f(x) return fn 发 ...
- ACM训练小结-2018年6月14日
于恢复性训练Day2情况如下:https://vjudge.net/contest/234651 先看A题,读懂题意,没有想明白,码完后连续多次WA,后找到错误AC. 对B题,发现其是一个 ...
- Linux操作系统的安装以及基本的操作命令详解
背景:使用的虚拟机安装Linux 虚拟机使用的是VMware Linux版本:CentOS-6.7-X86 自行下载:CentOS-6.7-x86_64-bin-DVD1.iso 打开VMw ...
- python爬虫-韩寒新浪博客博文
博客地址:http://blog.sina.com.cn/s/articlelist_1191258123_0_1.html 爬第一页博文 #-*-coding:utf--*- import re # ...
- 为mac编写swift脚本
代码示例: #!/usr/bin/env xcrun swift print("Hello World") 可以用Sublime Text编写,安装Swift包后有语法着色功能.然 ...