<h1>🌴 Tree Contructor</h1>
<br/>
<div id="example1"></div>
<div id="example2"></div>
<div id="example3"></div>
<div id="example4"></div>
const treeConstructor = (strArr) => {
  const treeObject = strArr.reduce((result, current) => {
    const [child, parent] = current.match(/\d+/g);
    result[parent] = result[parent] ? [...result[parent], child] : [child];

    return result;
  }, {});

  const isThereCommonChildren =
    Object.values(treeObject).reduce((result, current) =>
      result.filter((element) => current.includes(element))
    ).length > 0;

  const isParentHasTwoChildrenAtMax = Object.values(treeObject).every(
    (childrenArray) => childrenArray.length <= 2
  );

  const treeChildren = Object.values(treeObject).flat();

  const isSingleRootedTree =
    Object.keys(treeObject).filter((node) => !treeChildren.includes(node))
      .length === 1;

  return (
    !isThereCommonChildren && isParentHasTwoChildrenAtMax && isSingleRootedTree
  );
};

document.getElementById("example1").innerHTML =
  '["(1,2)", "(2,4)", "(7,2)"] => ' +
  treeConstructor(["(1,2)", "(2,4)", "(7,2)"]);

document.getElementById("example2").innerHTML =
  '["(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)"] => ' +
  treeConstructor(["(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)"]);

document.getElementById("example3").innerHTML =
  '["(1,2)", "(1,3)"] => ' + treeConstructor(["(1,2)", "(1,3)"]);

document.getElementById("example4").innerHTML =
  '["(3,2)", "(4,5)"] => ' + treeConstructor(["(3,2)", "(4,5)"]);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.