1. 程式人生 > >jS生成二叉樹,二叉樹的遍歷,查詢以及插入

jS生成二叉樹,二叉樹的遍歷,查詢以及插入


js遞迴,二叉樹的操作


//遞迴演算法n次冪
function foo(n) {

    if (n == 1) {
        return 1;
    } else {
        return n * foo(n - 1);
    }

}

//console.log(foo(3));var nodes = {
    name: 'root', childs: [
        { name: 'a1' },
        { name: 'a2' },
        { name: 'a3' },
        { name: 'b1' },
        { name: 'b2' },
        {
            name: 'b3', childs: [
                { name: 'bb1' },
                { name: 'bb2' },
                { name: 'bb3' }
            ]
        }
    ]
}

//遞迴樹形節點
function output(node) {

    console.log(node.name);

    if (node.childs && node.childs.length > 0) {
        node.childs.forEach(function (el, i) {
            //遞迴
            output(el);
        });
    }

}
//output(nodes);

//二叉樹
var tree = {
    value: 100,
    left: {
        value: 80,
        left: {
            value: 70
        },
        right: {
            value: 90
        }
    },
    right: {
        value: 200,
        left: {
            value: 180
        }, right: {
            value: 220
        }
    }
}
//二叉樹遍歷(遞迴演算法,容易導致執行棧溢位)
function printTree(tree) {

    console.log(tree.value)

    if (tree.left) {
        printTree(tree.left);
    }

    if (tree.right) {
        printTree(tree.right);
    }

}

//printTree(tree);

//二叉樹的查詢
var count = 0;
function findInTree(tree, v) {

    count++;

    if (v > tree.value && tree.right) {
        findInTree(tree.right, v)
    } else if (v < tree.value && tree.left) {
        findInTree(tree.left, v)
    } else if(v==tree.value){
        console.log('存在該節點,節點值為:',tree.value);
        return 0;
    }else{
        console.log('不存在該節點!');
        return -1;
    }

}

//findInTree(tree,70);
//console.log(count);
//二叉樹的插入
function insertTree(tree, v) {

    if (v > tree.value) {

        if (tree.right) {//如果有子節點繼續遍歷

            insertTree(tree.right, v);
        } else {
            tree.right = { value: v };
        }

    } else if (v < tree.value) {

        if (tree.left) {//如果有子節點繼續遍歷

            insertTree(tree.left, v);

        } else {
            tree.left = { value: v };
        }    } else {
        console.log('樹中已存在該節點');
    }
}

//insertTree(tree,505);
//console.log(tree);

//二叉樹的生成(以一個數組中的任意元素為樹的根節點)
var data = [12, 23, 45, 123, 5, 89, 42, 32, 69, 11, 87, 25];
//生成一個隨機的索引
var rindex = Math.floor(Math.random() * data.length);
//隨機獲取data中的一個元素作為二叉樹的根元素
var prodTree = { value: data[rindex] };

//使用根元素和陣列為引數 建立索引
function createTree(node, data) {

    data.forEach(function (v) {
        //將陣列的每個元素插入二叉樹中
        insertTree(node,v);
     
    });

}
createTree(prodTree,data);
//遍歷生成的二叉樹每個節點的值
printTree(prodTree);