码迷,mamicode.com
首页 > Web开发 > 详细

js二分查找树实现

时间:2019-01-09 00:33:24      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:===   key   实现   new   span   style   his   order   nbsp   

    function BinaryTree() {
        var Node = function(key) {
            this.key = key;
            this.left = null;
            this.right = null;
        }
        var root = null;
        var insertNode = function(node, newNode) {
            if (newNode.key < node.key){
                if(node.left === null) {
                    node.left = newNode;
                } else {
                    insertNode(node.left, newNode); 
                }

            } else {
                if (node.right === null) {
                    node.right = newNode;
                } else {
                    insertNode(node.right, newNode); 
                }
            }
        }
        this.insert = function(key) {
            var newNode = new Node(key);
            if(root === null){
                root = newNode;
            } else {
                insertNode(root, newNode)
            }
        }
        this.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,7,13];
    var binaryTree = new BinaryTree();
    nodes.forEach(function(key){
        binaryTree.insert(key);
    });
    var callback = function(key) {
        console.log(key)
    }

    binaryTree.inOrderTraverse(callback);
    

 

js二分查找树实现

标签:===   key   实现   new   span   style   his   order   nbsp   

原文地址:https://www.cnblogs.com/kbnet/p/10242025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!