I am trying to solve [this][1] problem where you need to create a binary tree that looks like this:
1
/ \
2 3
/ /
4 5
/ /
/ /\
/ / \
6 7 8
\ / \
\ / \
9 10 11
From this input where -1 represents a null node
[2 3] [4 -1] [5 -1] [6 -1] [7 8] [-1 9] [-1 -1] [10 11] [-1 -1] [-1 -1] [-1 -1]
Once you have done that, the problem asks you to swap nodes at a given depth.
So far I have this code that creates the tree:
(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)))])
I am totally stuck with how to swap the nodes, I have tried this function:
(defn walk-tree [node curr swap-depth]
(when node
(let [left (:left node)
right (:right node)
val (:val node)]
(if (= curr swap-depth)
(TreeNode. val (walk-tree right (inc curr) swap-depth) (walk-tree left (inc curr) swap-depth))
(TreeNode. val (walk-tree left (inc curr) swap-depth) (walk-tree right (inc curr) swap-depth))))))
But I think I should be going BFS rather than DFS because while I can swap a node this way, it gets swapped back when the right node is encountered.
-9in the example input, likely a typo. And do you need to swap nodes only at the given depth or deeper as well? And I believe DFS is just fine here, I would use it.-9typo, the first element should be[2 3], the last[-1 -1]should also be remove, right?