You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/*// Definition for a Node.class Node { public int val; public List<Node> children; public Node() { children = new ArrayList<Node>(); } public Node(int _val) { val = _val; children = new ArrayList<Node>(); } public Node(int _val,ArrayList<Node> _children) { val = _val; children = _children; }};*/classSolution {
publicNodefindRoot(List<Node> tree) {
Set<Node> childrenSet = newHashSet<>();
for (Nodenode : tree) {
for (Nodechild : node.children) {
childrenSet.add(child);
}
}
for (Nodenode : tree) {
if (!childrenSet.contains(node)) {
returnnode;
}
}
returnnull;
}
}
Runtime: 17 ms (Beats: 51.30%)
Memory: 50.04 MB (Beats: 67.83%)
Attempt 2: Use the sum of all node values
/*// Definition for a Node.class Node { public int val; public List<Node> children; public Node() { children = new ArrayList<Node>(); } public Node(int _val) { val = _val; children = new ArrayList<Node>(); } public Node(int _val,ArrayList<Node> _children) { val = _val; children = _children; }};*/classSolution {
publicNodefindRoot(List<Node> tree) {
intnodeSum = 0;
intchildSum = 0;
for (Nodenode : tree) {
nodeSum += node.val;
for (Nodechild : node.children) {
childSum += child.val;
}
}
inttargetVal = nodeSum - childSum;
for (Nodenode : tree) {
if (node.val == targetVal) {
returnnode;
}
}
returnnull;
}
}