根据二叉树创建字符串(https://leetcode.cn/problems/construct-string-from-binary-tree/description/)
题目描述:给你二叉树的根节点 root
,请你采用前序遍历的方式,将二叉树转化为一个由括号和整数组成的字符串,返回构造出的字符串。
空节点使用一对空括号对 "()"
表示,转化后需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
思路:
代码:
public String tree2str(TreeNode root) {
StringBuilder sub=new StringBuilder();
tree2strchild(root,sub);
return sub.toString();
}
public void tree2strchild(TreeNode root,StringBuilder sub) {
if(root==null){
return;
}
sub.append(root.val);
if(root.left!=null){
sub.append("(");
tree2strchild(root.left,sub);
sub.append(")");//走完时加右括号
}else{
if(root.right!=null){//左树为空右树不为空
sub.append("()");
}else{//左树为空右树也为空
return;
}
}
if(root.right!=null){//右树不为空
sub.append("(");
tree2strchild(root.right,sub);
sub.append(")");
}else{
return;
}