1 given [1, [2,3], [[4]]], return sum. 计算sum的方法是每向下一个level权重+1, 例子的sum = 1 * 1 + (2 + 3) * 2 + 4 * 3。follow up:每向下一个level 权重 - 1, sum = 3 * 1 +(2 + 3)* 2 + 4 * 1
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static class Node {
}
public static class ValNode extends Node {
int val;
public ValNode(int v) {
this.val = v;
}
}
public static class ListNode extends Node {
List<Node> nodes;
public ListNode() {
nodes = new ArrayList<Node>();
}
public void addNode(Node node) {
this.nodes.add(node);
}
}
public static int getWeightIncrease(Node node, int weight) {
int res = 0;
if (node instanceof ValNode) {
res += weight * ((ValNode) node).val;
} else {
ListNode list = (ListNode) node;
for (Node child : list.nodes) {
res += getWeightIncrease(child, weight + 1);
}
}
return res;
}
public static void main(String args[]) {
ListNode all = new ListNode();
Node node1 = new ValNode(1);
ListNode node2 = new ListNode();
node2.addNode(new ValNode(2));
node2.addNode(new ValNode(3));
ListNode node3 = new ListNode();
ListNode sub = new ListNode();
node3.addNode(sub);
sub.addNode(new ValNode(4));
all.addNode(node1);
all.addNode(node2);
all.addNode(node3);
System.out.println(getWeightIncrease(all, 0));
}
}
没有评论:
发表评论