share my java solution, straight!!!


  • 0
    T
    /**
     * 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 "";
            StringBuilder res=new StringBuilder();
            traverse(res,t);
            return res.toString();
        }
        
        public void traverse(StringBuilder res,TreeNode root){
            if(root==null){
                return;
            }
            
            res.append(root.val+"");
            
            if(root.left==null&&root.right==null){
                return;
            }
            
            res.append("(");
            if(root.left!=null){
                traverse(res,root.left);
            }
            res.append(")");
            
            if(root.right!=null){
                res.append("(");
                traverse(res,root.right);
                res.append(")");
            }
            
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.