用于打印完整二叉树的JavaScript函数

时间:2014-03-26 21:36:50

标签: javascript regex

我正在尝试创建一个JavaScript函数,它将完整二进制文件的HTML返回到一定数量的位。

例如,full_bintree(1)

会为

提供HTML
 /\
1  0

full_bintree(2)会为

提供HTML
    /\
   /  \
  1    0
 / \  / \ 
1   01   0

full_bintree(3)会为

提供HTML
          /\
         /  \
        /    \
       /      \
      /        \
     1          0
    / \        / \
   /   \      /   \
  1     0    1     0
 / \   / \  / \   / \
1   0 1   01   0 1   0

等等。

我开始做一个功能,但它看起来很糟糕,我一直在意识到我需要回去修复的问题。

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>";
    }
}

1 个答案:

答案 0 :(得分:2)

这是你的功能:

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.