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. 【kruscal】【最小生成树】poj2421 Constructing Roads

    SB题,求最小生成树,其中有些边已经给您建好啦. 随意暴力即可. #include<cstdio> #include<algorithm> #include<cstrin ...

  2. python基础-匿名函数、内置函数、正则表达式、模块

    1. 匿名函数 1.1 有名函数 有名函数:定义了一个函数名,函数名指向内存地址:通过函数名进行访问.函数名加括号就可以运行有名函数,例如:func() def func(x, y, z = 1): ...

  3. TZOJ 删除前导多余的*号

    描述 规定输入的字符串中只包含字母和*号,编写程序使字符串中前导的*号不得多于n个:若多于n个,则删除多余的*号:若少于或等于n个,则什么也不做,字符串中间和尾部的*号不删除. 输入 输入数据包括一串 ...

  4. python语言实现阶乘的两种方法---递归和迭代

    阶乘的递归实现,代码如下: def factorial(n): if n==1: return 1 else: return n*factorial(n-1) number = int(input(& ...

  5. linux-改变文件属主权限-chown

    http://www.cnblogs.com/peida/archive/2012/12/04/2800684.html chown将指定文件的拥有者改为指定的用户或组,用户可以是用户名或者用户ID: ...

  6. Wait statistics, or please tell me where it hurts

    https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/ By: Paul Rand ...

  7. Oracle RMAN 备份及不完全恢复(删除archievelog)

    RMAN备份命令 backup Database format='/home/oracle/backup/bak_full_%U_%T' tag='bak_full'; sql 'alter syst ...

  8. Java程序运行的内存分配

    Java的内存分配 A:栈 存储局部变量 B:堆 存储所有new出来的 C:方法区(程序代码及方法相关) D:本地方法区(系统相关) E:寄存器(CPU使用) 注意: a:局部变量 在方法定义中或者方 ...

  9. vulkan

    https://gfxbench.com/device.jsp?benchmark=gfx40&os=Android&api=gl&D=Asus+ZenFone+4+%28Ad ...

  10. D3.js系列——交互式操作和布局

    一.图表交互操作 与图表的交互,指在图形元素上设置一个或多个监听器,当事件发生时,做出相应的反应. 交互,指的是用户输入了某种指令,程序接受到指令之后必须做出某种响应.对可视化图表来说,交互能使图表更 ...