JavaScript Part (a) of the binary tree insertion (attachment: Visualization)

First, the concept of a binary tree

Binary tree (binary tree) is a tree, where each node can have more than two sons.

Byte side, a first binary word is inserted, where in fact, for a search tree binary insertion.

Making binary tree becomes a binary search tree property that for each tree node X, its left subtree is less than the value of all the items in X, and its right subtree is greater than all the values of X, items items.

The following diagram, two are binary tree, the tree on the left is to find a tree, the tree on the right is not. The right tree in the left subtree of nodes which item 6 (which happens to be root node), there is one node 7 items.

Next we want to achieve insertion of binary tree:

eg:  for [2, 5, 4, 1, 3, 6] => 

  

Second, the realization of ideas

  Examples of node 1. Node

  If the root node is empty, assigned to put newNode root node;

  If the root node exists, the new node is inserted.

  2. Insert the left or right subtree subtree

  1) If the node is less than newNode

    1. If node.left (left child) is empty, newNode assigned node.left

    2. Otherwise, again comparing newNode <node.left 

  2) If the node is greater than newNode

    1. If node.right (right child) is empty, newNode assigned node.right

    2. Otherwise, again comparing newNode> node.right

Third, code implementation

. 1  function BinaryTree () {
 2      // custom node 
. 3      var the Node = function (Key) {    
 . 4          the this .key = Key;
 . 5          the this .left = null ;
 . 6          the this .right = null ;
 . 7      }
 . 8      // initializes the root node 
9      var the root = null ;    
 10      // insert node 
. 11      the this .insert = function (Key) {    
 12 is          // instantiated node node 
13 is          var= newNode new new the Node (Key);
 14          // root node is empty, assigned to put newNode root node 
15          IF (root === null ) {
 16              root = newNode;
 . 17          } the else {
 18 is          // root exists, insertion the new node   
. 19              insertNode (the root, the newNode);
 20 is          };
 21 is      }
 22 is      // the insertion node (preorder) 
23 is      var insertNode = function (node, the newNode) {  
 24          // node of the current node 
25          // the newNode new node 
26         // If less than newNode node, the node is inserted into the left side 
27          IF (newNode.key < node.key) { 
 28              // If the left child node is null, the left child node is inserted into the 
29              IF (node.left === null ) {
 30                  node.left = the newNode;
 31 is              } the else {
 32              // If the left child node is not empty, then continue to the left child node and insertion of the comparison 
33 is                  insertNode (node.left, the newNode);
 34 is              }
 35          } the else {    
 36              IF (node.right === null ) {
 37 [                 node.right = newNode;
38             }else{
39                 insertNode(node.right, newNode);
40             }
41         }
42     }
43 }
var Nodes = [2,. 5,. 4,. 1,. 3,. 6 ]; 
 var BinaryTree = new new BinaryTree (); // array each element is inserted into the binary tree 
nodes.forEach ( function (Key) { 
    binaryTree.insert (Key); 
})

Annex: Visualization binary tree sorting, to understand better (Go:! Https://www.imooc.com/notepad/1fb575 )

<!DOCTYPE html>    

<html>    

<title>二叉排序树</title>    

    <head>    

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />    

    </head>    

    <body >    

        <canvas id="canvas" width="1366" height="768" ></canvas>

    </body>    

</html>    

    

<script type="text/javascript">

        //二叉算法函数    

       function BinaryTree(){

        //node 节点函数

        var Node=function(key){

            this.key=key;

            this.left=null;

            this.right=null;

            this= 0 .x; // graphics rendering coordinate 

            the this .y = 0; // graphic rendering coordinate 

        }; 



        / * * graphical depiction of a visual binary * * / 

        the this .graphical = []; // array of graphics 

        the this .lrMove = 100 ; // left offset 

        the this .udMove = 100; // vertical offset 

        / * * * ================== * / 



        // define root 

        var the root = null ; 



        // insert node loop around a recursive function drop 

        the this .insertNode = function (node, the newNode) { 

            IF (newNode.key < node.key) { 

                IF (node.left === null){

                    var x = node.x;

                    var y = node.y;

                    newNode.x = (x -= this.udMove); 

                    newNode.y = (y += this.lrMove);

                    node.left=newNode;     

                }else{

                    this.insertNode(node.left,newNode);

                }

            }else{

                if(node.right===null){

                    var x = node.x;

                    var y = node.y;

                    newNode.x = (x += this.udMove); 

                    newNode.y = (y += this.lrMove);

                    node.right=newNode;

                }else{

                    this.insertNode(node.right,newNode);

                }

            }

        };



        //入口程序

        this.insert=function(key){

            var newNode= new Node(key);

            if(root===null){

                root=newNode;

                root.x = 500;

                root.y = 100;

                this.graphical.push(root);

            }else{

                this.insertNode(root,newNode);

            }

        };



        var inOrdertraverseNode = function(node,callback){

            if(node !== null){

                inOrdertraverseNode(node.left,callback);

                callback(node.key);

                inOrdertraverseNode(node.right,callback);

            }

        }



        this.inOrdertraverse = function(callback){

            inOrdertraverseNode(root,callback);

        }

    }



    var nodes=[8,3,10,1,6,14,4,15,12,13];

    var binaryTree=new BinaryTree;

    for(var i = 0 ; i < nodes.length ; i++){

         binaryTree.insert(nodes[i]);

    }



    var callback = function(key){

        console.log(key)

    }



    binaryTree.inOrdertraverse(callback);



    /*=====================================================开始绘制================================*/

    var canvas = document.getElementById("canvas");

    var context = canvas.getContext('2d');  // Get the corresponding 2D objects (brush) 





    function Draw (Key, X, Y) { 

        the this .counter = 0 ; 

        the this .render = function (C) { 

            c.fillStyle = "HSL (" + the this .counter + ", % 100, 50%) " ; 

            c.strokeStyle = '#fff'; // set the stroke color 

            c.font =" Bold 40px 'font', 'font', 'Microsoft elegant black', 'Times New Roman' "; / / set Font 

            c.textBaseline = 'Hanging'; // current text baseline used in rendering the text 

            c.fillText (Key, X, Y); 

        } 

        the this .update = function(){

          this+ =. 5 .counter ; 

        } 

    } 



    var fontCavaseArr = []; 



     function the init () { 

        Loop (); // draw text         

        the setInterval (RUN, 1000/30);
 
      } 





    function RUN (X, Y) { 

      context.fillStyle = " RGBA (0,0,0,0.1) " ; 

      context.fillRect ( 0,0,1366,768); // draw 1366 * 768 pixels of filled rectangle: 

      for (I = 0; I <fontCavaseArr.length; I ++ ) { 

        var Particle = fontCavaseArr [I]; 

        particle.render (context); 

        particle.update (); 

      }

      gLine();//绘制线条

    }



    function loop(){

        font(binaryTree.graphical[0]);

    }



    function font(obj){

        if(obj.key != null && obj.key != undefined){

            var drawFont = new draw(obj.key,obj.x,obj.y);

            fontCavaseArr.push(drawFont);

        }

        if(obj.left != null && obj.left != undefined){

            var drawFont = new draw(obj.left.key,obj.left.x,obj.left.y);

            fontCavaseArr.push(drawFont);

            font(obj.left);

        }

        if(obj.right != null && obj.right != undefined){

            var drawFont = new draw(obj.right.key,obj.right.x,obj.right.y);

            fontCavaseArr.push(drawFont);

            font(obj.right);

        }

    }



    function gLine(){

        line(binaryTree.graphical[0]);

    }

    

    function line(obj){

        context.lineJoin="round";  

        context.lineCap="butt";  

        context.beginPath(); 

        if(obj.left != null && obj.left != undefined){

            context.moveTo(obj.x+20,obj.y+20); 

            context.lineTo(obj.left.x+20,obj.left.y+20);

            context.stroke();  

            context.closePath(); 

            line(obj.left);

        }

        if(obj.right != null && obj.right != undefined){

            context.moveTo(obj.x+20,obj.y+20); 

            context.lineTo(obj.right.x+20,obj.right.y+20);

            context.stroke();  

            context.closePath(); 

            line(obj.right);

        }

    }

    

    init();



</script>    
View Code

 

Guess you like

Origin www.cnblogs.com/zzcyeah/p/11070395.html