August 5, 2018

4clojure 130 - Tree reparenting

Every node of a tree is connected to each of its children as well as its parent. One can imagine grabbing one node of a tree and dragging it up to the root position, leaving all connections intact. For example, below on the left is a binary tree. By pulling the "c" node up to the root, we obtain the tree on the right.

Tree

Note it is no longer binary as "c" had three connections total – two children and one parent. Each node is represented as a vector, which always has at least one element giving the name of the node as a symbol. Subsequent items in the vector represent the children of the node. Because the children are ordered it's important that the tree you return keeps the children of each node in order and that the old parent node, if any, is appended on the right. Your function will be given two args – the name of the node that should become the new root, and the tree to transform.

The code below is running live in your browser. Complete the tree-reparent function to make the unit tests pass. Check out the next post for the solution.

(ns live.test
  (:require [cljs.test :refer-macros [deftest is run-tests]]))
  
(defn tree-reparent [e t]
  )
  
(deftest test-130
  (is (= '(n) (tree-reparent 'n '(n))))
  (is (= '(a (t (e))) (tree-reparent 'a '(t (e) (a)))))
  (is (= '(e (t (a))) (tree-reparent 'e '(a (t (e))))))
  (is (= '(a (b (c))) (tree-reparent 'a '(c (b (a))))))
  (is (= '(d (b (c) (e) (a (f (g) (h))))) (tree-reparent 'd '(a (b (c) (d) (e)) (f (g) (h))))))
  (is (= '(c (d) (e) (b (f (g) (h)) (a (i (j (k) (l)) (m (n) (o)))))) (tree-reparent 'c '(a (b (c (d) (e)) (f (g) (h))) (i (j (k) (l)) (m (n) (o))))))))
 
(run-tests)
Tags: coding exercises KLIPSE 4clojure Clojure