JSFiddle - React, Tailwind, and code Playground

by gravi2

HTML

<canvas id="tree" width="500" height="400"
style="border:1px solid #000000;">
</canvas>

JavaScript

function Node(n,parent) {
    
    this.value = n;
    this.left = null;
    this.right = null;
    this.parent = parent;    
    this.cx = 0;
    this.cy= 0;
    
    
    this.draw = function() {
        this.depth = this.parent!= null ? this.parent.depth + 1 : 0;
        var c=document.getElementById("tree");
        var radius = 20;
        var distance = ((radius*2) + 10) * this.depth ;
        console.log('----' + this.value + '....' + this.parent + ">>> " + this.depth);
        //calculate the cx,cy based on the distance
        //from the parent cx,cy
        if ( this.parent == null ) {
            this.cx = (c.width/2);
            this.cy = distance;
        } else if (this.parent.left && this.parent.left.value == this.value)  {
            //render as left node
            this.cx = this.parent.cx - distance;
            this.cy = this.parent.cy + distance;
        } else if (this.parent.right && this.parent.right.value == this.value) {
            //render as right node
            this.cx = this.parent.cx + distance;
            this.cy = this.parent.cy + distance;
        }

        // finally draw the circle
        var ctx=c.getContext("2d");
        ctx.beginPath();
        ctx.arc(this.cx,this.cy,radius,0,2*Math.PI);
        ctx.stroke();
        
        // draw the value
        ctx.strokeText(this.value,this.cx,this.cy);
        
        // draw the line from parent center to node center
        if (this.parent) {
            ctx.beginPath();
            ctx.moveTo(this.parent.cx,this.parent.cy);
            ctx.lineTo(this.cx,this.cy);
            ctx.stroke();
        }
    };
}



function BST() {
    this.root = null;
    
    this.init = function(items) {
        for (i=0;i<items.length;i++) {
            var node = new Node(items[i]);
            this.add(node,this.root);
        }
    };
    
    this.add = function(node,parent) {
        if (this.root == null ){
            this.root = node;
        } else if (parent.value <...