问题:有一颗苹果树,以二叉树存储,给出他的两点之间的边和每个苹果的重量,给出的重量为1,默认的为0,从任何节点找到最大的重量和?
算法:
public class PingGuoShu {
static int max = 0;
public static void main(String[] args) {
int[] value1 = { 2, 3, 4 };
int[][] data1 = {{1,2},
{1, 3},
{1, 4}
};
int n = 4;
int[] value = new int[n + 1];
for(int i = 0; i < value1.length; i++){
value[value1[i]] = 1;
}
int[] data = new int[n + 1];
for(int i = 0; i < data1.length; i ++){
data[data1[i][1]] = data1[i][0];
}
int[] vis = new int[n + 1];
for(int i = 1; i <= n; i++){
vis[i] = 1;
find(data, i, value[i], vis, value);
vis[i] = 0;
System.out.println(max);
}
}
private static void find(int[] data, int i, int num, int[] vis, int[] value) {
max = max > num ? max : num;
for(int j = 0; j < data.length; j++){
if(data[j] == i && vis[j] == 0){
vis[j] = 1;
find(data, j, num + value[j], vis, value);
vis[j] = 0;
}
}
if(vis[data[i]] == 0 && data[i] != 0){
vis[data[i]] = 1;
find(data, data[i], num + value[data[i]], vis, value);
vis[data[i]] = 0;
}
}
}