设为首页 加入收藏

TOP

图解数据结构树之AVL树(二)
2019-08-14 00:07:59 】 浏览:116
Tags:图解 数据结构 AVL
ngleRotateWithRight(T->m_pRight); return singleRotateWithLeft(T); } AvlTree AvlTreeInsert(AvlTree T, DataType x) { if(T == NULL) //如果树为空 { T = (AvlNode *)malloc(sizeof(struct AvlNode)); if(T) { T->data = x; T->m_pLeft = NULL; T->m_pRight = NULL; T->height = 0; } else { cout << "空间不够" << endl; exit(0); } } else if( x < T->data) //如果插入到T结点的左子树上 { T->m_pLeft = AvlTreeInsert(T->m_pLeft,x); //先插入,后旋转 if(Height(T->m_pLeft) - Height(T->m_pRight) == 2) //只有可能是这个 { if(x < T->m_pLeft->data) //左左情况,只需要右旋转 { T = singleRotateWithRight( T ); } else //左右情况,双旋转,先左 { T = doubleRotateWithLeft( T ); } } } else if( x > T->data ) { T->m_pRight = AvlTreeInsert(T->m_pRight,x); if(Height(T->m_pRight) - Height(T->m_pLeft) == 2) { if(x > T->m_pRight->data) //右右情况,进行左旋 { T = singleRotateWithLeft( T ); } else //左右情况,双旋转,先右 { T = doubleRotateWithRight( T ); } } } //如果这个数已经存在,那么不进行插入 T->height = Max(Height(T->m_pLeft),Height(T->m_pRight)) + 1; return T; } //递归实现中序遍历 void inOrderVisitUseRecur(const AvlTree pCurrent) { if(pCurrent) { inOrderVisitUseRecur(pCurrent->m_pLeft); cout << pCurrent->data << " "; if(pCurrent->m_pLeft) cout << " leftChild: "<<pCurrent->m_pLeft->data; else cout << " leftChild: "<<"NULL" ; if(pCurrent->m_pRight) cout << " rightChild: "<<pCurrent->m_pRight->data; else cout << " rightChild: "<< "NULL"; cout << endl; inOrderVisitUseRecur(pCurrent->m_pRight); } } int main() { AvlTree root = NULL; root = AvlTreeInsert(root,1); root = AvlTreeInsert(root,2); root = AvlTreeInsert(root,3); root = AvlTreeInsert(root,4); root = AvlTreeInsert(root,5); root = AvlTreeInsert(root,6); root = AvlTreeInsert(root,7); root = AvlTreeInsert(root,8); root = AvlTreeInsert(root,9); root = AvlTreeInsert(root,10); root = AvlTreeInsert(root,11); root = AvlTreeInsert(root,12); root = AvlTreeInsert(root,13); root = AvlTreeInsert(root,14); root = AvlTreeInsert(root,15); inOrderVisitUseRecur(root); return 0; }
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C语言编译过程 下一篇C语言编程入门之--第五章C语言基..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目