606. Construct String from Binary Tree 【easy】

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.

差一点AC的代码:

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
string tree2str(TreeNode* t) {
string result; if (t == NULL) {
return "";
} result += to_string(t->val); if (t->left) {
result += "(" + tree2str(t->left) + ")";
} if (t->right) {
result += "(" + tree2str(t->right) + ")";
} return result;
}
};

实际上对应的图如下图,可以发现需要对左子树为空,右子树不为空的情况做个特殊判断。

解法一:

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
string tree2str(TreeNode* t) {
string result; if (t == NULL) {
return "";
} result += to_string(t->val); if (t->left) {
result += "(" + tree2str(t->left) + ")";
}
else if (t->right) {
result += "()";
} if (t->right) {
result += "(" + tree2str(t->right) + ")";
} return result;
}
};

上面代码中第24 ~ 26行就是对左子树为空,右子树不为空的情况做的特殊判断。

解法二:

 class Solution {
public:
string tree2str(TreeNode* t) {
return !t ? "" : to_string(t->val) + (t->left ? "(" + tree2str(t->left) + ")" : t->right ? "()" : "")
+ (t->right ? "(" + tree2str(t->right) + ")" : "");
}
};

参考@alexander 的代码。

解法三:

 public class Solution {
public String tree2str(TreeNode t) {
if (t == null) return ""; String result = t.val + ""; String left = tree2str(t.left);
String right = tree2str(t.right); if (left == "" && right == "") return result;
if (left == "") return result + "()" + "(" + right + ")";
if (right == "") return result + "(" + left + ")";
return result + "(" + left + ")" + "(" + right + ")";
}
}

最后集中起来再判断的思路很好,参考@shawngao 的代码。

解法四:

 public String tree2str(TreeNode t) {
StringBuilder sb = new StringBuilder();
helper(sb, t);
return sb.toString();
}
public void helper(StringBuilder sb, TreeNode t) {
if (t != null) {
sb.append(t.val); if(t.left != null || t.right != null) {
sb.append("(");
helper(sb, t.left);
sb.append(")"); if(t.right != null) {
sb.append("(");
helper(sb, t.right);
sb.append(")");
}
}
}
}

606. Construct String from Binary Tree 【easy】的更多相关文章

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

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

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

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

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

  4. 606. Construct String from Binary Tree

    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 解题报告

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

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

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

  8. 606. Construct String from Binary Tree 从二叉树中构建字符串

    [抄题]: You need to construct a string consists of parenthesis and integers from a binary tree with th ...

  9. Python 解LeetCode:606 Construct String from Binary Tree

    题目描述:用先序遍历的方式把二叉树转换成字符串,其中结点用括号分割,具体示例见题目链接 思路: 先序遍历,先把根结点的值转化成字符串,然后递归的把左右子树的值转化成字符串 把1中的根结点和左右子结点的 ...

随机推荐

  1. Find the Difference -- LeetCode

    Given two strings s and t which consist of only lowercase letters. String t is generated by random s ...

  2. Codeforces 311E Biologist

    Discription SmallR is a biologist. Her latest research finding is how to change the sex of dogs. In ...

  3. 【分块】bzoj3295 [Cqoi2011]动态逆序对

    考虑每次删除pos位置一个数x后,所造成的的影响就是,逆序对的个数少了在1~pos-1中大于x的数的个数加上pos+1~n中小于x的数的个数. 那么我们需要的操作就只有查询区间内比某数大(小)的个数. ...

  4. 【tarjan求割顶】BZOJ2730-[HNOI2012]矿场搭建

    [题目大意] 煤矿工地可以看成是由隧道连接挖煤点组成的无向图.为安全起见,希望在工地发生事故时所有挖煤点的工人都能有一条出路逃到救援出口处.于是矿主决定在某些挖煤点设立救援出口,使得无论哪一个挖煤点坍 ...

  5. 杂谈PID控制算法——第一篇:三个量

    电赛训练了大半个暑假,人渐渐开始进入到了疲倦期.既然这样那就好好休息下自己也好吧. 休息也不能光休息,乘机把平常写过的一些东西好好整理也好. 从第一次训练开始我们就接触到了一个新的名词——PID控制理 ...

  6. SQL SERVER 常用命令

    红色为常用 0.row_number() over 和数据组合sale/cnt select *,row_number() over(order by productname) as rownumbe ...

  7. 使用ab.exe监测100个并发/100次请求情况下同步/异步访问数据库的性能差异

    ab.exe介绍 ab.exe是apache server的一个组件,用于监测并发请求,并显示监测数据 具体使用及下载地址请参考:http://www.cnblogs.com/gossip/p/439 ...

  8. BigDecimal类整除报错的解决方案

    例如: BigDecimal num1 = new BigDecimal("10"); BigDecimal num2 = new BigDecimal("3" ...

  9. PostgreSQL配置文件--WAL

    3 WAL WRITE AHEAD LOG 3.1 Settings 3.1.1 fsync 字符串 默认: fsync = on 开启后强制把数据同步更新到磁盘,可以保证数据库将在OS或者硬件崩溃的 ...

  10. 基于CentOS与VmwareStation10搭建Oracle11G RAC 64集群环境:3.安装Oracle RAC-3.1.安装并配置ASM驱动

    3.1.安装并配置ASM驱动 3.3.1.检查内核 [root@linuxrac2 etc]# uname -r 2.6.18-164.el5 下载以下rpm包(注意rpm包版本和Linux内核版本一 ...