title: Change a tree root
body: <p>I am trying to write an algorithm to change a tree root.
  Tree is represented as an array: <code>['A', ['B', ['D']], ['C']]</code>.</p>
  
  <p>I wrote some algorithm that uses recursion but it doesn't work correctly for all test cases that I wrote. Can't find a mistake. Also maybe someone remember examples how to solve that.</p>
  
  <p>My code:</p>
  
  <pre><code>   const change_root_ = (node: Tree, target: string, prevNode: Tree): Tree =&gt; {
        if (!node) {
          return node;
        }
  
        const nodeLabel = node[0];
  
        if (nodeLabel === target) {
          return [
            ...node,
            prevNode
          ];
        }
  
        const leftNode = node[1];
        if (leftNode) {
          return change_root_(
            leftNode,
            target,
            [...node.slice(0, 1), ...node.slice(2)]
          );
        }
  
        const rightNode = node[2];
        return change_root_(rightNode, target, [...node.slice(0, 2)]);
      }
  
      const change_root = (tree: Tree, newRootLabel: string): Tree =&gt; {
        return change_root_(tree, newRootLabel);
      };
  </code></pre>
  
  <p>Here you can see the actual code + test cases at the bottom. <a href="http://jsbin.com/noyeponove/edit?js,console,output" rel="nofollow noreferrer">http://jsbin.com/noyeponove/edit?js,console,output</a></p>