二叉树节点查找与删除 发表于 2017-09-30 | 分类于 JavaScript 在上一篇关于二叉树的js实现的基础上,增加二叉树节点查找与删除操作。 代码如下: 注意:接口写在BinaryTree()中,部分代码已省略 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122function BinaryTree(){ //... //最小值查找 this.min = function(){ return minNode(root); } function minNode(node){ if (node) { while(node && node.left !== null){ node = node.left; } return node.text; } return null; } //最大值查找 this.max = function(){ return maxNode(root); } function maxNode(node){ if (node) { while(node && node.right !== null){ node = node.right; } return node.text; } return null; } //判断某值是否存在 this.search = function(text){ return searchNode(root,text); } function searchNode(node,text){ if (!node) { return false; }else if(text>node.text){ return searchNode(node.right,text); }else if(text<node.text){ return searchNode(node.left,text) }else{ return true; } } //删除节点 this.remove = function(text){ root = removeNode(root,text); } function removeNode(node,text){ if (node === null) { return null; } if (text<node.text) { node.left = removeNode(node.left,text); return node; }else if (text>node.text) { node.right = removeNode(node.right,text); return node; }else { if (node.left === null && node.right === null) { node = null; return node; } if (node.left === null) { node = node.right; return node; }else if (node.right === null) { node = node.left; return node; } var aux =findMinNode(node.right); node.text = aux.text; node.right = removeNode(node.right,aux.text); return node; } } function findMinNode(node){ if (node) { while(node && node.left !== null){ node = node.left; } return node; } return null; } //...} //查找最小值//console.log(binaryTree.min());//查找最大值//console.log(binaryTree.max());//判断值是否存在//console.log(binaryTree.search(7) ? '7 is found' : '7 is no found');//console.log(binaryTree.search(9) ? '9 is found' : '9 is no found');//删除节点//binaryTree.remove(10);