BiruLyu
7/10/2017 - 8:28 PM

606. Construct String from Binary Tree(1st).java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public String tree2str(TreeNode t) {
        if (t == null) return "";
        
        String result = t.val + "";
        
        String left = tree2str(t.left);
        String right = tree2str(t.right);
        
        if (left == "" && right == "") return result;
        if (left == "") return result + "()" + "(" + right + ")";
        if (right == "") return result + "(" + left + ")";
        return result + "(" + left + ")" + "(" + right + ")";
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    StringBuilder s = new StringBuilder();    
    
    public String tree2str(TreeNode t) {
        tree2strSB(t);
        return s.toString();
    
    }
    
    
    public void tree2strSB(TreeNode t) {
        
        if(t==null) return;
        s.append(String.valueOf(t.val));
        
        if(t.right == null && t.left == null) return;
        
        s.append("(");
        tree2strSB(t.left);
        s.append(")");
        
        if(t.right==null) return;
        
        s.append("(");
        tree2strSB(t.right);
        s.append(")");
        return;
    }
}