原题链接在这里: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的更多相关文章

  1. [LeetCode] Construct String from Binary Tree 根据二叉树创建字符串

    You need to construct a string consists of parenthesis and integers from a binary tree with the preo ...

  2. 606. Construct String from Binary Tree 【easy】

    606. Construct String from Binary Tree [easy] You need to construct a string consists of parenthesis ...

  3. 【Leetcode_easy】606. Construct String from Binary Tree

    problem 606. Construct String from Binary Tree 参考 1. Leetcode_easy_606. Construct String from Binary ...

  4. 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 ...

  5. 【LeetCode】606. Construct String from Binary Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:先序遍历 日期 题目地址:https://l ...

  6. LeetCode算法题-Construct String from Binary Tree(Java实现)

    这是悦乐书的第273次更新,第288篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第141题(顺位题号是606).构造一个字符串,该字符串由二叉树中的括号和整数组成,并具 ...

  7. LeetCode 606 Construct String from Binary Tree 解题报告

    题目要求 You need to construct a string consists of parenthesis and integers from a binary tree with the ...

  8. [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 ...

  9. 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 ...

随机推荐

  1. linux练习命令

    任务一:按要求完成以下操作1)显示日期格式2)在/tmp/下新建目录test ,并指定权限6643)显示环境变量path,但将/root加入到$PATH中4)用cat显示/etc/passwd,并打印 ...

  2. iOS 系统认知 debug distribution release 和 #ifdef DEBUG

    debug:调试模式 有调试信息 线下 release: 无调试信息 经过了编译优化 发布 给用户使用的 线上模式  一般 工程项目 都是自带 上述两种配置结构 还有出现 distribution: ...

  3. UI控件之UITextField

    UITextField:文本框:用来输入一行文本,父类是UIControl UITextField *field1=[[UITextField alloc]initWithFrame:CGRectMa ...

  4. nand flash详解及驱动编写

    https://www.crifan.com/files/doc/docbook/linux_nand_driver/release/html/linux_nand_driver.html#nand_ ...

  5. php面向对象之克隆对象

    在前面的PHP面向对象之对象和引用,我们试图以"$b=$a"的方式复制对象以传递对象的值(内容),结果却是传递对象的地址,在结尾为了解决复制对象这个问题,提到了克隆的方法.接下来讲 ...

  6. Virtual Container Hosts(VCHs) 介绍

    In vSphere Integrated Containers, you deploy virtual container hosts (VCHs) that serve as Docker API ...

  7. Kubernetes Storage

    参考文章: https://kubernetes.io/docs/concepts/storage/volumes/ https://www.cnblogs.com/styshoo/p/6731425 ...

  8. K8s API

    https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#daemonset-v1-apps http://docs.k ...

  9. centos7下安装jdk7

     CentOS7.1 JDK安装 1.卸载自带OPENJDK    用 java -version 命令查看当前jdk版本信息   #java -version    用rpm -qa | grep ...

  10. Elasticsearch安装笔记

    下载安装包 wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.5.2.zip 开始执行bin/./el ...