Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 457995
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T22:37:37+00:00 2026-05-12T22:37:37+00:00

Let’s say I have a binary tree data structure defined as follows type ‘a

  • 0

Let’s say I have a binary tree data structure defined as follows

type 'a tree =
    | Node of 'a tree * 'a * 'a tree
    | Nil

I have an instance of a tree as follows:

let x =
  Node
    (Node (Node (Nil,35,Node (Nil,40,Nil)),48,Node (Nil,52,Node (Nil,53,Nil))),
     80,Node (Node (Nil,82,Node (Nil,83,Nil)),92,Node (Nil,98,Nil)))

I’m trying to pretty-print the tree into something easy to interpret. Preferably, I’d like to print the tree in a console window like this:

        _______ 80 _______
       /                  \
    _ 48 _              _ 92 _
   /      \            /      \
 35       52         82       98
   \       \        /
    40      53    83

What’s an easy way to get my tree to output in that format?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T22:37:37+00:00Added an answer on May 12, 2026 at 10:37 pm

    If you want it to be very pretty, you could steal about 25 lines of code from this blog entry to draw it with WPF.

    But I’ll code up an ascii solution shortly too, probably.

    EDIT

    Ok, wow, that was hard.

    I’m not certain it’s entirely correct, and I can’t help but think there’s probably a better abstraction. But anyway… enjoy!

    (See the end of the code for a large example that is rather pretty.)

    type 'a tree =    
        | Node of 'a tree * 'a * 'a tree
        | Nil
    
    (*
    For any given tree
         ddd
         / \
       lll rrr  
    we think about it as these three sections, left|middle|right (L|M|R):
         d | d | d
         / |   | \
       lll |   | rrr  
    M is always exactly one character.
    L will be as wide as either (d's width / 2) or L's width, whichever is more (and always at least one)
    R will be as wide as either ((d's width - 1) / 2) or R's width, whichever is more (and always at least one)
         (above two lines mean 'dddd' of even length is slightly off-center left)
    We want the '/' to appear directly above the rightmost character of the direct left child.
    We want the '\' to appear directly above the leftmost character of the direct right child.
    If the width of 'ddd' is not long enough to reach within 1 character of the slashes, we widen 'ddd' with
        underscore characters on that side until it is wide enough.
    *)
    
    // PrettyAndWidthInfo : 'a tree -> string[] * int * int * int
    // strings are all the same width (space padded if needed)
    // first int is that total width
    // second int is the column the root node starts in
    // third int is the column the root node ends in
    // (assumes d.ToString() never returns empty string)
    let rec PrettyAndWidthInfo t =
        match t with
        | Nil -> 
            [], 0, 0, 0
        | Node(Nil,d,Nil) -> 
            let s = d.ToString()
            [s], s.Length, 0, s.Length-1
        | Node(l,d,r) ->
            // compute info for string of this node's data
            let s = d.ToString()
            let sw = s.Length
            let swl = sw/2
            let swr = (sw-1)/2
            assert(swl+1+swr = sw)  
            // recurse
            let lp,lw,_,lc = PrettyAndWidthInfo l
            let rp,rw,rc,_ = PrettyAndWidthInfo r
            // account for absent subtrees
            let lw,lb = if lw=0 then 1," " else lw,"/"
            let rw,rb = if rw=0 then 1," " else rw,"\\"
            // compute full width of this tree
            let totalLeftWidth = (max (max lw swl) 1)
            let totalRightWidth = (max (max rw swr) 1)
            let w = totalLeftWidth + 1 + totalRightWidth
    (*
    A suggestive example:
         dddd | d | dddd__
            / |   |       \
          lll |   |       rr
              |   |      ...
              |   | rrrrrrrrrrr
         ----       ----           swl, swr (left/right string width (of this node) before any padding)
          ---       -----------    lw, rw   (left/right width (of subtree) before any padding)
         ----                      totalLeftWidth
                    -----------    totalRightWidth
         ----   -   -----------    w (total width)
    *)
            // get right column info that accounts for left side
            let rc2 = totalLeftWidth + 1 + rc
            // make left and right tree same height        
            let lp = if lp.Length < rp.Length then lp @ List.init (rp.Length-lp.Length) (fun _ -> "") else lp
            let rp = if rp.Length < lp.Length then rp @ List.init (lp.Length-rp.Length) (fun _ -> "") else rp
            // widen left and right trees if necessary (in case parent node is wider, and also to fix the 'added height')
            let lp = lp |> List.map (fun s -> if s.Length < totalLeftWidth then (nSpaces (totalLeftWidth - s.Length)) + s else s)
            let rp = rp |> List.map (fun s -> if s.Length < totalRightWidth then s + (nSpaces (totalRightWidth - s.Length)) else s)
            // first part of line1
            let line1 =
                if swl < lw - lc - 1 then
                    (nSpaces (lc + 1)) + (nBars (lw - lc - swl)) + s
                else
                    (nSpaces (totalLeftWidth - swl)) + s
            // line1 right bars
            let line1 =
                if rc2 > line1.Length then
                    line1 + (nBars (rc2 - line1.Length))
                else
                    line1
            // line1 right padding
            let line1 = line1 + (nSpaces (w - line1.Length))
            // first part of line2
            let line2 = (nSpaces (totalLeftWidth - lw + lc)) + lb 
            // pad rest of left half
            let line2 = line2 + (nSpaces (totalLeftWidth - line2.Length))
            // add right content
            let line2 = line2 + " " + (nSpaces rc) + rb
            // add right padding
            let line2 = line2 + (nSpaces (w - line2.Length))
            let resultLines = line1 :: line2 :: ((lp,rp) ||> List.map2 (fun l r -> l + " " + r))
            for x in resultLines do
                assert(x.Length = w)
            resultLines, w, lw-swl, totalLeftWidth+1+swr
    and nSpaces n = 
        String.replicate n " "
    and nBars n = 
        String.replicate n "_"
    
    let PrettyPrint t =
        let sl,_,_,_ = PrettyAndWidthInfo t
        for s in sl do
            printfn "%s" s
    
    let y = Node(Node (Node (Nil,35,Node (Node(Nil,1,Nil),88888888,Nil)),48,Node (Nil,777777777,Node (Nil,53,Nil))),     
                 80,Node (Node (Nil,82,Node (Nil,83,Nil)),1111111111,Node (Nil,98,Nil)))
    let z = Node(y,55555,y)
    let x = Node(z,4444,y)
    
    PrettyPrint x
    (*
                                       ___________________________4444_________________
                                      /                                                \
                          ________55555________________                         ________80
                         /                             \                       /         \
                ________80                      ________80             _______48         1111111111
               /         \                     /         \            /        \            /  \
       _______48         1111111111    _______48         1111111111 35         777777777  82   98
      /        \            /  \      /        \            /  \      \             \       \
    35         777777777  82   98   35         777777777  82   98     88888888      53      83
      \             \       \         \             \       \            /
      88888888      53      83        88888888      53      83           1
         /                               /
         1                               1
    *)     
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 217k
  • Answers 217k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Try using oci_parse instead of OCIParse. And oci_execute instead of… May 12, 2026 at 11:24 pm
  • Editorial Team
    Editorial Team added an answer The correct way to do this under windows is to… May 12, 2026 at 11:24 pm
  • Editorial Team
    Editorial Team added an answer MODbus is like a lot of old protocols and really… May 12, 2026 at 11:24 pm

Related Questions

I have a French site that I want to parse, but am running into
Let's say you create a wizard in an HTML form. One button goes back,
Let's say I'm building a data access layer for an application. Typically I have
Let's say you have a class called Customer, which contains the following fields: UserName
Let me try to explain what I need. I have a server that is

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.