import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// 我的思路是,从树的叶子开始计算
// 到底是这个节点的开心值大,还是这个节点的子节点加起来开心值大
// 如果是前者, 返回该节点的开心值,后者, 返回这个节点子节点的开心值
public class Finder{
public static Node node;
//传入数据的方法
static{
// 创建老板,开心度为5
node = new Node(new ArrayList<Node>(), 5);
// 创建两个员工,开心度分别为 1, 2
node.subNodes.add(new Node(null, 1));
node.subNodes.add(new Node(null, 2));
}
// 获得最大快乐的方法
public static int getMaxHappy(Node root) {
// 如果root == null, 返回开心值 0
if(root == null) {
return 0;
}
// 如果有子节点,而且子节点元素不为空,返回最大开心值
else if(root.subNodes != null && !root.subNodes.isEmpty()) {
Iterator<Node> iterator = root.subNodes.iterator();
int happys = 0;
while(iterator.hasNext()) {
happys += getMaxHappy(iterator.next());
}
return root.happy > happys ? root.happy : happys;
}
// 如果没有子节点,返回当前节点开心值
else {
return root.happy;
}
}
public static void main(String[] args) {
int maxHappy = Finder.getMaxHappy(Finder.node);
System.out.println(maxHappy);
}
}
class Node{
List<Node> subNodes;
int happy;
public Node(List<Node> subNodes, int happy) {
this.subNodes = subNodes;
this.happy = happy;
}
}