HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Finding the sum of the digits appearing in the leaves via in-order traversal

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theorderdigitsfindingleavesappearingviasumtraversal

Problem

The following text is an in-order traversal of a binary tree with 1023
nodes. What is the sum of the digits appearing in the leaves?

How can I improve this Clojure code? It looks strange to me to have two recurs in the if.

(ns fun2)

(defn parse [in sum]
 (println "sum" sum)
 (if (> (.length in) 1)
   (let [next-char (subs in 0 1)]
     (if (.matches next-char "[0-9]")
       (recur (subs in 2) (+ sum (Integer/parseInt next-char)))
       (recur (subs in 2) sum)))))

(parse (slurp "/Users/clojure/challange2.txt") 0)

;; ans 331

Solution

Here's a version of the function that I find nicer:

(defn parse [s]
  (apply + (->> s
             (partition-all 2)                 ; iterate pairs of chars in s
             (map (comp str first))            ; leaf node is the first in the pair
             (filter (partial re-find #"\d"))  ; keep only digits
             (map #(Integer/parseInt %)))))    ; turn 'em into ints


I imagine it can be further reduced to be more idiomatic Clojure, but I find this pretty readable.

Important assumption: this algorithm only works if the input is an inorder traversal of a complete binary tree. If the original tree was not complete, a single inorder traversal is not sufficient to reconstruct it and find the leaves.

Code Snippets

(defn parse [s]
  (apply + (->> s
             (partition-all 2)                 ; iterate pairs of chars in s
             (map (comp str first))            ; leaf node is the first in the pair
             (filter (partial re-find #"\d"))  ; keep only digits
             (map #(Integer/parseInt %)))))    ; turn 'em into ints

Context

StackExchange Code Review Q#3475, answer score: 5

Revisions (0)

No revisions yet.