Java stack limit

I encountered severe problems with Java’s stack limit. With many silver issues, I can’t really use recursions to solve them (for example, December Silver Problem 1). What should I do?

Could you post your code?

import java.io.*;
import java.util.*;
public class BarnTree {
	static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
	static long[] hays;
	static long[] subsums;
	static long count = 0;
	static ArrayList<String> orders;
	static PrintWriter pr = new PrintWriter(System.out);
	public static void main(String[] args) throws IOException{
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		long average = 0;
		hays = new long[n+1];
		subsums =new long[n+1];
		StringTokenizer st = new StringTokenizer(br.readLine());
		for(int i  = 1;i<=n;i++) {
			hays[i] = Integer.parseInt(st.nextToken());
			average += hays[i];
		}
		average /= n;
		for(int i = 1; i<=n;i++) hays[i] -= average;
		for(int i = 0;i<=n;i++) adj.add(new ArrayList<Integer>());
		for(int i = 0;i<n-1;i++) {
			//System.out.println(i);
			StringTokenizer curl = new StringTokenizer(br.readLine());
			int a = Integer.parseInt(curl.nextToken());
			int b = Integer.parseInt(curl.nextToken());
			adj.get(a).add(b);
			adj.get(b).add(a);
		}
		orders = new ArrayList<String>();
		dfssum(1,1);
		dfsprint(1,1);
		pr.println(count);
		for(String o:orders) pr.println(o);
		pr.close();
	}
	static long dfssum(int cur, int last) {
		long cursum = hays[cur];
		for(int next:adj.get(cur)) if(next!=last) cursum+=dfssum(next,cur);
		subsums[cur] = cursum;
		return cursum;
	}
	static void dfsprint(int cur,int last) {
		for(int next:adj.get(cur)) {
			if(subsums[next]>0&&next!=last)dfsprint(next,cur);
		}
		for(int next:adj.get(cur)) {
			if(subsums[next]<0&&next!=last) {
				long toadd = subsums[next];
				StringBuilder sb =new StringBuilder();
				sb.append(cur).append(" ").append(next).append(" ").append(-toadd);
				orders.add(sb.toString());
				count++;
				dfsprint(next,cur);
			}
		}
		if(subsums[cur]>0&&cur!=1) {
			long toadd = subsums[cur];
			StringBuilder sb =new StringBuilder();
			sb.append(cur).append(" ").append(last).append(" ").append(toadd);
			orders.add(sb.toString());
			count++;
		}
	}

}

Looks like your solution is wrong (the number of orders is not the minimum possible).