js二分查找树实现
程序员文章站
2022-06-30 18:31:16
function BinaryTree() { var Node = function(key) { this.key = key; this.left = null; this.right = null; } var root = null; var ... ......
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);