java solution using pre-order and replace


  • 0
    L
    public String tree2str(TreeNode t) {
            StringBuffer buffer  = new StringBuffer("");
            preTravelHelper(buffer,t);
            return buffer.toString().replace("()()","").replace("())",")").replace(")()",")");
        }
        
        private void preTravelHelper(StringBuffer buffer,TreeNode t){
            if(t == null) return;
            buffer.append(t.val);
            buffer.append("(");
            preTravelHelper(buffer,t.left);
            buffer.append(")(");
            preTravelHelper(buffer,t.right);
            buffer.append(")");
        }
    

Log in to reply
 

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