Untitled
unknown
plain_text
a month ago
821 B
1
Indexable
import java.util.*; public class NAryTreeTraversals { // Inorder Traversal for N-ary Tree public List<Integer> inorder(Node root) { List<Integer> result = new ArrayList<>(); inorderHelper(root, result); return result; } private void inorderHelper(Node node, List<Integer> result) { if (node == null) return; int n = node.children.size(); for (int i = 0; i < n; i++) { // Visit the first half of the children if (i == n / 2) { result.add(node.val); // Visit the root } inorderHelper(node.children.get(i), result); } // If there are no children, add the root (edge case) if (n == 0) { result.add(node.val); } } }
Editor is loading...
Leave a Comment