Appearance
0606-根据二叉树创建字符串
https://leetcode.cn/problems/construct-string-from-binary-tree
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
示例 1:
输入: 二叉树: [1,2,3,4] 1 /
2 3 /
4
输出: "1(2(4))(3)"
解释: 原本将是“1(2(4)())(3())”, 在你省略所有不必要的空括号对之后, 它将是“1(2(4))(3)”。 示例 2:
输入: 二叉树: [1,2,3,null,4] 1 /
2 3 \ 4
输出: "1(2()(4))(3)"
解释: 和第一个示例相似, 除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。
思路
dfs 递归,注意左括号和右括号是分别对应左节点和右节点的。
当左节点为空右节点不为空时,也要输出左节点。
参考代码
csharp
public class Solution {
public string Tree2str(TreeNode root) {
if(root == null){
return "";
}
string result = root.val+"";
// 注意左节点的输出条件是,左节点不为空
// 或者左节点为空但右节点不为空时【此时左节点会输出 ()】
if(root.left!=null || root.right != null){
result +="(";
result += Tree2str(root.left);
result += ")";
}
if(root.right!=null){
result += "(";
result += Tree2str(root.right);
result += ")";
}
return result;
}
}
AlgoPress