Skip to content

Instantly share code, notes, and snippets.

@dagda1
Last active August 29, 2015 14:27
Show Gist options
  • Save dagda1/499772c530244dcd935f to your computer and use it in GitHub Desktop.
Save dagda1/499772c530244dcd935f to your computer and use it in GitHub Desktop.
(ns scratch.core
(require [clojure.string :as str :only (split-lines join split)]))
(defn numberify [str]
(vec (map read-string (str/split str #" "))))
(defrecord TreeNode [val left right])
(defn preprocess-input [n xs]
(let [source (map vector (range 1 n) xs)]
(->> source
(map (fn [[k v]]
{k v}))
(into {}))))
(defn build-tree [val source]
(when-let [[l r] (get source val)]
(TreeNode. val (build-tree l source) (build-tree r source))))
(let [input "11\n2 3\n4 -1\n5 -1\n6 -1\n7 8\n-1 9\n-1 -1\n10 11\n-1 -1\n-1 -1\n-1 -1\n2\n2\n4"
lines (str/split-lines input)
tree-length (read-string (first lines))
tree-lines (map numberify (drop 1 (take (inc tree-length) lines)))
tree-source (preprocess-input tree-length tree-lines)
tree (build-tree 1 tree-source)
swap-depths (map read-string (vec (take-last (Integer/parseInt (get lines (inc tree-length))) lines)))])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment