美文网首页JavaScript与数据结构
JavaScript数据结构10——二叉树的遍历

JavaScript数据结构10——二叉树的遍历

作者: RichardW | 来源:发表于2017-03-27 14:07 被阅读0次
    function BTNode(data) {
        this.data = data;
    }
    BTNode.prototype.setLC = function(node){
        this.leftchild = node;
    }
    BTNode.prototype.setRC = function(node){
        this.rightchild = node;
    }
    //前序遍历
    function preOrderTraverse(Btree){
        if(Btree==null){
            return;
        }
        console.info(Btree.data);
        preOrderTraverse(Btree.leftchild);
        preOrderTraverse(Btree.rightchild);
    }
    //中序遍历
    function inOrderTraberse(Btree){
        if(Btree==null){
            return;
        }
        inOrderTraberse(Btree.leftchild);
        console.info(Btree.data);
        inOrderTraberse(Btree.rightchild);
    }
    //后序遍历
    function postOrderTraberse(Btree){
        if(Btree==null){
            return;
        }
        postOrderTraberse(Btree.leftchild);
        postOrderTraberse(Btree.rightchild);
        console.info(Btree.data);
    }
    var nodeA = new BTNode('A');
    var nodeB = new BTNode('B');
    var nodeC = new BTNode('C');
    var nodeD = new BTNode('D');
    var nodeE = new BTNode('E');
    var nodeF = new BTNode('F');
    var nodeG = new BTNode('G');
    var nodeH = new BTNode('H');
    var nodeI = new BTNode('I');
    var nodeJ = new BTNode('J');
    var nodeK = new BTNode('K');
    nodeA.setLC(nodeB);
    nodeA.setRC(nodeC);
    nodeB.setLC(nodeD);
    nodeB.setRC(nodeE);
    nodeD.setLC(nodeH);
    nodeH.setRC(nodeK);
    nodeC.setLC(nodeF);
    nodeC.setRC(nodeG);
    nodeF.setLC(nodeI);
    nodeG.setRC(nodeJ);
    console.info('前序遍历');
    preOrderTraverse(nodeA);
    console.info('中序遍历');
    inOrderTraberse(nodeA);
    console.info('后序遍历');
    postOrderTraberse(nodeA);
    

    结果显而易见

    前序遍历
    ABDHKECFIGJ
    中序遍历
    HKDBEAIFCGJ
    后序遍历
    KHDEBIFJGCA

    相关文章

      网友评论

        本文标题:JavaScript数据结构10——二叉树的遍历

        本文链接:https://www.haomeiwen.com/subject/tylrottx.html