首页 > 编程知识 正文

avl树删除节点,avl树和二叉树的区别主要是

时间:2023-05-04 17:26:38 阅读:154119 作者:4887

把算法笔记的代码齐了

《算法笔记》 P327

主要是LL、LR、RR、RL几种旋转调整、height的获得、平衡因子的获得

代码:

# include stdio.h # includealgorithmusingnamespacestd; struct node{int v,height; node *lchild; node *rchild; (; //新节点node*newnode(intv ) {node* Node=new node; Node-v=v; 节点高度=1; Node-lchild=Node-rchild=NULL; 返回节点; 以root为根节点子树的当前heightintgetheight(node*root ) if ) root==null ) return 0; 返回根高度; //节点root的平衡因子intgetbalancefactor(node*root ) return getheight (root-lchild )-getheight (root-rchild ); //节点root的heightvoidupdateheight (node * root ) root-height=max (getheight ) root-lchild (getheight ) root ) root searchAVL树的数据字段搜索x的节点voidsearch(node*root,int x ) (if ) root==null ) (打印) ) searchfailedn ' ); 返回; (if ) x==root-v ) printf )、root-v ); }elseif(xroot-v ) search ) root-lchild,x ); }else{search(root-rchild,x ); }//此AVL树voidinorder(node*root ) if ) root==null ) {return; }else{inorder(root-lchild ); printf('%d ',root-v ); 节点(root-rchild ); }//左旋voidL(node*root ) {node* temp=root-rchild; root-rchild=temp-lchild; temp-lchild=root; 更新高度(root; 更新高度(temp; 根=时间; //右转voidr(node*root ) {node* temp=root-lchild; root-lchild=temp-rchild; temp-rchild=root; 更新高度(root; 更新高度(temp; 根=时间; //插入权重v的节点voidinsert(node*root,int v ) if ) root==null ) root=newnode ) v ); 返回; }if(vroot-v ) insert ) root-lchild,v ); 更新高度(root; getbalancefactor (root )=2(if ) getbalancefactor (root-lchild )==1 ) root ); } else if (getbalancefactor (root-lchild )=-1 ) ) l ) root-lchild; r (根); }}else{insert(root-rchild,v ); 更新高度(root; getbalancefactor (root )=-2 (if ) getbalancefactor (root-rchild )=-1 (l ) root ); } else if (getbalancefactor (root-rchild )==1) r ) root-rchild ); l (路线); }//创建AVL树node*creat(intdata[],int n ) {node* root=NULL; for(intI=0; i n; I ) insert(root,data[i]; }return root; } int main () intdata(10 )={ 1,2,4,6,3,5,7,9,8,10 }; node*linshi=creat(data,10 ),调换这些数字的顺序,在得到的AVL树中按顺序遍历相同的node* root=NULL; printf (中顺扫描这一AVL树的输出为:(n ); inorder(Linshi ); 在printfnAVL树中搜索100个节点的数据域n '; 搜索(linshi,100 ); }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。