最大堆—链表实现

  在上一篇文章中提到了二叉树的三叉链表实现,在本文中我们实现了最大推(最小堆算法类似)。在最大堆中要注意的问题是,最大堆是在完全二叉树的基础上实现的。由于上一篇中我们已经实现了二叉树,所以在此我们就不给你二叉树的代码。

#include
#include"binaryTreeNode.h"
#include"binaryTree.h"
#include
#include
using namespace std;
void maxHeap(binaryTreeNode * root, stack< binaryTreeNode * > &s)// find all the non-leafnode and store them in the stack "s".
{
  queue< binaryTreeNode * > q;
  if(NULL!=root)
  q.push(root);
  while(!q.empty())
  {
   root=q.front();
   if(root->getLeftChild()!=NULL||root->getRightChild()!=NULL)
   s.push(root);

   q.pop();
   if(root->getLeftChild())
   q.push(root->getLeftChild());
   if(root->getRightChild())
   q.push(root->getRightChild());
  }


}
void SWAP(binaryTreeNode * b1,binaryTreeNode *b2)// swap the data of two node
{
 int tep;
 tep=b1->getData();
 b1->setData(b2->getData());
 b2->setData(tep);
}
void sift(binaryTreeNode * cur)// if find one subtree that do not satisfy the condition of maxheap,then adjust it
{
 while(cur->getLeftChild())//because the tree is a complete binary tree, so you just need to judge the leftchlid
 {
  if(cur->getData()getLeftChild()->getData()
   &&(cur->getRightChild()==NULL||cur->getRightChild()->getData()getLeftChild()->getData()))
  {
   SWAP(cur,cur->getLeftChild());
   cur=cur->getLeftChild();
  }
  else if(cur->getRightChild()!=NULL&&cur->getData()getRightChild()->getData()
   &&cur->getLeftChild()->getData()getRightChild()->getData())
  {
   SWAP(cur,cur->getRightChild());
   cur=cur->getRightChild();
  }
  else
   return;
 }
}

void main()
{
 binaryTreeNode *t1,*t3,*t4,*t5,*t6;
 binaryTree tree1(20);
 t1=tree1.getRoot();
 tree1.insertLeftChild(t1,12);
 tree1.insertRightChild(t1,35);
 t3=t1->getLeftChild();
 tree1.insertLeftChild(t3,15);
 tree1.insertRightChild(t3,10);
 t4=t1->getRightChild();
 tree1.insertLeftChild(t4,80);
 tree1.insertRightChild(t4,30);
 t5=t3->getLeftChild();
 tree1.insertLeftChild(t5,17);
 tree1.insertRightChild(t5,2);
 t6=t3->getRightChild();
 tree1.insertLeftChild(t6,1);
    cout<<"before adjustment:"<    tree1.leverOrderTraverse(t1);

    stack< binaryTreeNode * > s;
 maxHeap(t1,s);
 while(!s.empty())
  {
   t3=s.top();
   sift(t3);
   //cout<getData()<   s.pop();
  
  }
  cout<<"after adjustment:"<     tree1.leverOrderTraverse(t1);


}

 

 

 

你可能感兴趣的:(c++)