简体   繁体   English

JavaScript函数可打印出完整的二叉树

[英]JavaScript function to print out a full binary tree

I'm trying to make a JavaScript function that returns the HTML for a full binary up to a certain number of bits. 我正在尝试制作一个JavaScript函数,该函数返回HTML的完整二进制数(最多一定位数)。

For instance, full_bintree(1) 例如, full_bintree(1)

would give the HTML for 将为

 /\
1  0

and full_bintree(2) would give the HTML for full_bintree(2)将为

    /\
   /  \
  1    0
 / \  / \ 
1   01   0

and full_bintree(3) would give the HTML for full_bintree(3)将为

          /\
         /  \
        /    \
       /      \
      /        \
     1          0
    / \        / \
   /   \      /   \
  1     0    1     0
 / \   / \  / \   / \
1   0 1   01   0 1   0

and so forth. 等等。

I started to make a function but it's looking horrible and I keep realizing problems that I need to go back and fix. 我开始制作一个函数,但是看起来很糟糕,并且我不断意识到需要回去解决的问题。

function full_bintree(var b)
{
    var retstr = "";
    var nr = (2 << b) + (b - 1); // number of rows
    for (var i = 0, j = nr - 1, k = 0; i < nr; ++i, --j, k += 2)
    {
        retstr += "<p>";
        // Add leading spaces on line
        for (var m = 0; m < j; ++m)
            retstr += " ";
        // Add backslashes or 

        // Add middle spaces
        for (var m = 0; m < k; ++m)
            retstring += " ";
        // Add forward slashes 
        retstr += "</p>";
    }
}

Here's your function: 这是您的功能:

var logtree = function(A){
    for(var i = 0; i < A.length; i++)
        A[i] = A[i].join("");
    A = A.join("\n");
    if(typeof $ != "undefined")
        $("#a").html(A);
    console.log(A);
    return A;
},
bintree = function(n, A, offset, lvl){
    if(typeof offset == "undefined") offset = 0;
    if(typeof lvl == "undefined") lvl = 0;
    var width = 3 * Math.pow(2, n) - 1,
        height = Math.ceil(width / 2),
        mid = Math.floor(width / 2),
        half = Math.ceil(height / 2),
        nsub = Math.pow(2, lvl),
        lim = offset + half - 1,
        l = "/",
        r = "\\";
    if(typeof A == "undefined"){
        A = [];
        for(var i = 0; i < height; i++){
            a = [];
            for(var j = 0; j < width; j++) a.push(" ");
            A[i] = a;
        }
    }
    for(var i = offset, inc = 0; i <= lim; i++){
        if(i == lim){
            l = 1;
            r = 0;
        }
        var a = 0, j = 0;
        for(var j = 0; j < nsub; j++){
            A[i][mid - inc + a - 1] = l;
            A[i][mid + inc + a + 1] = r;
            a += width + 1;
        }
        inc++;
    }
    if(n > 1)
        bintree(n - 1, A, offset + height / 2, ++lvl);
    return A;
};
logtree(bintree(4));

and here's the fiddle. 这是小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM