*这篇整理大多都是从研讨课同学的PPT上拉下来的,故为转载。
*图片,部分是笔记照片,部分是网络图片。
*代码,应该是有从网上直接拉下来的,也有同学自己敲的,个人没有运行测试过,不过无碍于理解。
一、研讨题目:
1.建立树的算法。
-按先序遍历序列补空。
-按层序补空。
-按根结点【同时指明左右子树根结点】创建。
-按先序【后序】和中序序列构造。
2.二叉树的层序遍历,指定的某结点所在层数,指定某一层的结点数。
3.二叉树的后序非递归实现。
栈+二叉链表示。
三叉链。
二、内容整理:
1.建立树的算法。
①按先序遍历序列补空。
例:ABD##E##C##
顺序:根-左-右
补空如下:
②按层序补空。
例:层序遍历:425136
③按根结点【同时指明左右子树根结点】创建。
代码:
template<class Type> BinaryTree<Type> :: BinaryTree(Type *a, int n, Type x)
{
int i;
BinTreeNode<Type> *pl, *pr, *r;
cirqueue<BinTreeNode<Type>*>q;
if (a[0] == x)
{
cout << "整棵树的根结点的值不能为空!" << endl;
exit(1);
}
root = new BinTreeNode<Type>(a[0], NULL, NULL);
q.EnQueue(root);
for (i = 1; i < n-1; i+=2)
{
if ((a[i] == x) && (a[i+1] == x))
{
continue;
}
if (a[i] != x)
pl = new BinTreeNode<Type>(a[i], NULL, NULL);
else
pl = NULL;
if (a[i+1] != x)
pr = new BinTreeNode<Type>(a[i+1], NULL, NULL);
else
pr = NULL;
r = q.DeQueue();
if (!r)
{
cout << "应该有值,却为空。不知到哪里出错了,请检查程序!" << endl;
exit(1);
}
while (r->data != a[i/2])
r = q.DeQueue();
r->SetLeftChild(pl);
r->SetRightChild(pr);
if (pl)
q.EnQueue(pl);
if (pr)
q.EnQueue(pr);
}
}
④按先序【后序】和中序序列构造。
按先序和中序序列构造:
例:
2.二叉树的层序遍历,指定的某结点所在层数,指定某一层的结点数。
要点总结:
这道题可以分为三个部分来看:①二叉树的层序遍历;②指定某结点所在层数;③指定某一层的节点数。每一部分的功能都可以在前一代码的基础上增加。代码如下:
代码1:
【通过队列来实现二叉树的层序遍历】
template<class type>
void BinaryTree<type>::LevelOrder()
{
queue<BinTreeNode<type>*> q;
BinTreeNode<type> *p=root;
if(p)
q.EnQueue(p);
while(!q.IsEmpty())
{
p=q.DeQueue();
cout<<p->data<<" ";
if(p->GetLeftChild())
q.EnQueue(p->GetLeftChild());
if(p->GetRightChild())
q.EnQueue(p->GetLeftChild());
}
}
代码2:
【在代码1基础上增加了对层数的统计】
template<class type>
void BinaryTree<type>::LocateLevel(type x)
{
BinTreeNode<type> *p=root;
int lev=0,tag,temp;
if(!p)
cout<<"是空树!";
else
q.EnQueue(p);
tag=q.GetRear();
while(!q.IsEmpty())
{
p=q.DeQueue()=temp;
//cout<<p->data<<" ";
if(p->GetLeftChild())
q.EnQueue(p->GetLeftChild());
if(p->GetRightChild())
q.EnQueue(p->GetLeftChild());
if(tag==q.GetFront()) //队首指针
{
lev++;
tag=q.GetRear(); //队尾指针
if(temp==x)
cout<<"为第"<<lev<<"层";
}
else
if(temp==x)
cout<<"为第"<<lev+1<<"层"<<endl;
}
}
代码3:
【在代码2基础上再增加一个计数器即可。】
3.二叉树的后序非递归实现。
①栈+二叉链表示。
代码:
template<class Type>void BinaryTree<Type>::NonRecursePostOrder()
{
BinTreeNode<Type>*p=root;
SeqStack<BinTreeNode<Type>*>snode;//存放进栈之树结点
SeqStack<bool>stag;//存放进栈之标志
do
{
while(p!=NULL)
{
snode.Push(p);
stag.Push(false);
p=p->GetLeftChild();
}
if(stag.IsEmpty()==0)
{
//预出栈
if(stag.GetTop()==false)
{
p=snode.GetTop();
stag.Pop();
stag.Push(true);
p=p->GetRightChild();
}
else//出栈并打印
{
p=snode.Pop();
stag.Pop();
cout<<p->GetData()<<" ";
p=NULL;
}
}
}while(snode.IsEmpty()==0);
}
②三叉链。