binary_sort 二叉树
生活随笔
收集整理的這篇文章主要介紹了
binary_sort 二叉树
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
二叉樹的實(shí)現(xiàn) ?introduction to algorithm ?英文版實(shí)現(xiàn) ,中文版的實(shí)現(xiàn)跟英文版本略有不同,個(gè)人覺得中文版本換key的方式更好,英文版換了2次指針
function BinaryTree(){this.root=null; } BinaryTree.prototype.inorder_tree_walk=function(x){if(typeof x=='undefined'){x=this.root;}if(!!x){this.inorder_tree_walk(x.left);console.log(x.key);this.inorder_tree_walk(x.right);} } BinaryTree.prototype.tree_search=function(x,key){if(typeof x=='undefined'){x=this.root;}if(x==null||key==x.key){return x;}if(key<x.key){return this.tree_search(x.left,key);}else{return this.tree_search(x.right,key);} } BinaryTree.prototype.minimun=function(x){while(x.left!=null){return this.minimun(x.left);}return x; } BinaryTree.prototype.maximun=function(x){while(x.right!=null){return this.maximun(x.right);}return x; } BinaryTree.prototype.successor=function(x){if(x.right!=null){return this.minimun(x.right);}var y=x.parent;while(y!=null&&x==y.right){x=y;y=y.parent;}return y; } BinaryTree.prototype.predecessor=function(x){if(x.left!=null){return this.maximun(x.left);}var y=x.parent;while(y!=null&&x==y.left){x=y;y=y.parent;}return y; } /*node {left:null,right:null,key}*/ BinaryTree.prototype.insert=function(node){var y=null;var x=this.root;while(x!=null){y=x;if(node.key<x.key){x=x.left;}else{x=x.right;}}node.parent=y;if(y==null){this.root=node;}else if(node.key<y.key){y.left=node;}else{y.right=node;} } function _transplant(t,u,v){if(u.parent==null){// delete node ,node left null,node parent null => node.right to be root;// delete node ,node right null,node parent null => node.left to be root; t.root=v;}else if(u==u.parent.left){//delete node is its parent left nodeu.parent.left=v;}else{//delet node is its parent right node;u.parent.right=v;}if(v!=null){// fix pointer;v.parent=u.parent;} } BinaryTree.prototype.delete=function(node){if(node.left==null){_transplant(this,node,node.right);}else if(node.right==null){_transplant(this,node,node.left);}else{var y=this.minimun(node.right);if(y.parent!=node){// successor left node must be null;_transplant(this,y,y.right);y.right=node.right;y.right.parent=y;}_transplant(this,node,y);y.left=node.left;y.left.parent=y;} }后繼 和 前繼 ?的 2中特殊情況
delete的 3種情況 以 最后一種 有雙親最為復(fù)雜,紅黑樹的實(shí)現(xiàn)基于二叉樹,下一波就要繼續(xù)review 紅黑樹的代碼了,慣例以后補(bǔ)圖
經(jīng)過幾種場(chǎng)景的測(cè)試,二叉樹是一種不平衡的樹,依賴于insert的順序,最差的查找情況就是 n,跟鏈表一樣
?
轉(zhuǎn)載于:https://www.cnblogs.com/horsefefe/p/5724225.html
總結(jié)
以上是生活随笔為你收集整理的binary_sort 二叉树的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: R可视化lend_club 全球最大的P
- 下一篇: Zmodem transfer canc