Given the basis of a binary tree, assemble a string consisting of parenthesis and integers from a binary tree with the preorder traversal method, and return it.
Omit all of the empty parenthesis pairs that don’t have an effect on the one-to-one mapping relationship between the string and the unique binary tree.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode proper;
* TreeNode(int x) { val = x; }
* }
*/
public class Answer {
public String tree2str(TreeNode t) {
if(t==null)
return "";
if(t.left==null && t.proper==null)
return t.val+"";
if(t.proper==null)
return t.val+"("+tree2str(t.left)+")";
return t.val+"("+tree2str(t.left)+")("+tree2str(t.proper)+")";
}
}