Untitled
To find the root of an š N-ary tree given as a list of nodes, we can use the following approach: Approach Each node has a unique value. The root node is the only node that does not appear as a child in any other node's children list. To find the root: Maintain a set of all node values. Iterate through all the nodes and remove all the child values from this set. At the end, the only remaining value in the set is the root value. Algorithm Initialize a set with all the values from the nodes. Iterate through each node and remove its children values from the set. The remaining value in the set is the root value. class Node { int val; List<Node> children; Node(int val) { this.val = val; this.children = new ArrayList<>(); } } public class FindRootOfNaryTree { public static int findRoot(Node[] tree) { // Step 1: Add all node values to a set Set<Integer> nodeValues = new HashSet<>(); for (Node node : tree) { nodeValues.add(node.val); } // Step 2: Remove all child values from the set for (Node node : tree) { for (Node child : node.children) { nodeValues.remove(child.val); } } // Step 3: The remaining value in the set is the root return nodeValues.iterator().next(); } }
Leave a Comment