C#LeetCode刷题之#606-根据二叉树创建字符串（Construct String from Binary Tree）

1
/   \
2     3
/
4

1
/   \
2     3
\
4

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.

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)”.

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.

```public class Program {

public static void Main(string[] args) {
var t = new TreeNode(1) {
left = new TreeNode(2),
right = new TreeNode(3)
};
t.left.left = new TreeNode(4);

var res = Tree2str(t);
Console.WriteLine(res);

t = new TreeNode(1) {
left = new TreeNode(2),
right = new TreeNode(3)
};
t.left.right = new TreeNode(4);

res = Tree2str2(t);
Console.WriteLine(res);

}

private static string Tree2str(TreeNode t) {
if(t == null) return "";
var res = t.val.ToString();
if(t.left != null) {
res += '(' + Tree2str(t.left) + ')';
} else if(t.right != null) {
res += "()";
}
if(t.right != null) res += '(' + Tree2str(t.right) + ')';
return res;
}

private static string Tree2str2(TreeNode t) {
var sb = new StringBuilder();
return sb.ToString();
}

private static void SearchAndAdd(TreeNode t, StringBuilder sb) {
if(t == null) return;
sb.Append(t.val);
if(t.left != null) {
sb.Append("(");
sb.Append(")");
}
if(t.right != null) {
if(t.left == null) sb.Append("()");
sb.Append("(");
sb.Append(")");
}
}

public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}

}```

```1(2(4))(3)
1(2()(4))(3)```