LeetCode606-根据二叉树创建字符串

题目链接

英文链接:https://leetcode.com/problems/construct-string-from-binary-tree/

中文链接:https://leetcode-cn.com/problems/construct-string-from-binary-tree/

题目详述

你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。

空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。

示例 1:

1
2
3
4
5
6
7
8
9
10
11
12
输入: 二叉树: [1,2,3,4]
1
/ \
2 3
/
4

输出: "1(2(4))(3)"

解释: 原本将是“1(2(4)())(3())”,
在你省略所有不必要的空括号对之后,
它将是“1(2(4))(3)”。

示例 2:

1
2
3
4
5
6
7
8
9
10
11
输入: 二叉树: [1,2,3,null,4]
1
/ \
2 3
\
4

输出: "1(2()(4))(3)"

解释: 和第一个示例相似,
除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。

题目详解

  • 按先序遍历二叉树来构建字符串,需要注意的是要不要加 ()
  • 如果左子树和右子树均不为空,左子树和右子树均需要加 ()
  • 如果左子树为空,右子树不为空,左子树和右子树均需要加 ()
  • 如果左子树为不为空,右子树为空,左子树需要加 (),右子树不需要加 ()
  • 如果左子树和右子树均不为空,左子树和右子树均不需要加 ()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LeetCode_00606 {

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

为了提高效率可以用 StringBuilder 来拼接字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class LeetCode_00606 {

public String tree2str(TreeNode t) {
StringBuilder sb = new StringBuilder();
dfs(t, sb);
return sb.toString();
}

private void dfs(TreeNode t, StringBuilder sb) {
if (t == null) {
return;
}
sb.append(t.val);
if (t.left != null) {
sb.append('(');
dfs(t.left, sb);
sb.append(')');
}
if (t.right != null) {
if (t.left == null) {
sb.append("()");
}
sb.append('(');
dfs(t.right, sb);
sb.append(')');
}
}
}