Search code examples
javascripthtmlcssbinary-search-tree

How to display a binary search tree using CSS, HTML and a bit of Javascript?


I want to "paint" the tree on screen using CSS and HTML and not represent it in any way or data structure ...


Solution

  • A very simple way of creating a tree-like structure with HTML and CSS is nesting <div>s
    Each div represents a node, and can have multiple nodes inside:

    <div> //root
        <div> //child 1
            <div> //child 1.1
                <div></div> //child 1.1.1
                <div></div> //child 1.1.2
                <div></div> //child 1.1.3
            </div>
            <div></div> //child 1.2
        </div>
        <div></div> //child 2
    </div>
    

    Then you can add a margin-top to all divs, so that they appear under its parent div.

    A JSFiddle: http://jsfiddle.net/VxRmc/

    I've added percentage widths to each div. You can calculate widths if you know how many childs a node has. Or you can use fixed widths...

    Yeah, it's not a beautiful tree, but it can't be simpler.