HardPro challengeJavaScriptTypeScript

Tree Multi-Select

ReactTreesAlgorithms

Given a tree where each node has { id, children? }, and a set of
selected ids, propagate selections so:

  • If all children are selected, the parent is selected.
  • If no children are selected, the parent is not selected.
  • A leaf is selected iff in the input set.

solve(tree, selectedIds) returns sorted array of all selected ids.

Sample tests

Test #1All children → parent
Input: [{"id":"root","children":[{"id":"a"},{"id":"b"}]},["a","b"]]
Output: ["a","b","root"]
Test #2Partial → parent not selected
Input: [{"id":"root","children":[{"id":"a"},{"id":"b"}]},["a"]]
Output: ["a"]
Test #3Single leaf
Input: [{"id":"root"},["root"]]
Output: ["root"]
Test #4Deep tree, all selected
Input: [{"id":"r","children":[{"id":"a","children":[{"id":"a1"},{"id":"a2"}]},{"id":"b"}]},["a1","a2","b"]]
Output: ["a","a1","a2","b","r"]
Test #5Nothing selected
Input: [{"id":"r","children":[{"id":"a"},{"id":"b"}]},[]]
Output: []