【Leetcode刷题第二天】606. 根据二叉树创建字符串[JAVA] 一起来刷题吧~
题目描述:
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
示例 1:
输入: 二叉树: [1,2,3,4]
输出: “1(2(4))(3)”
解释: 原本将是“1(2(4)())(3())”,
在你省略所有不必要的空括号对之后,
它将是“1(2(4))(3)”。
示例 2:
输入: 二叉树: [1,2,3,null,4]
输出: “1(2()(4))(3)”
来源:力扣(LeetCode)
代码如下:
class Solution {
StringBuilder str=new StringBuilder();//StringBuilder的append()方法添加括号
public String tree2str(TreeNode root) {
DFS(root);
return str.toString();
}
void DFS(TreeNode root){
if(root==null){
return;
}
str.append(root.val);//.val获得root域的值
if(root.left!=null){
str.append('(');
DFS(root.left);
str.append(')');
}
if(root.left==null&&root.right!=null){
str.append("()");
}
if(root.right!=null){
str.append('(');
DFS(root.right);
str.append(')');
}
}
}
总结:
这道题目在leetcode上的描述有点… 看懂题目就会简单很多。题目的大体意思就是:
左右子树都存在,那就每个都包()继续递归
只有左子树,只给左子树包()继续递归
只有右子树,左子树用()表示,右子树包()继续递归
一定要理解题目意思~
最后大家一起来刷题吧~