数据结构------二叉树的基本构建与基本操作
- 之前又儿子兄弟法构建过一次树,这次使用最普通的二叉树的左右节点法构建二叉树。
- 主要实现三种遍历方式,外加一种逐层输出的方法。
- 遇到了几个无伤大雅的小问题:1.M++,++M在函数调用时的先后问题。2.在递归调用后的整数,无法恢复的问题。可能要借助& 先放下留作问题。
- 上测试用例图:
- 下面附上代码
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct Node//数据类型作为整形
{
int data;
struct Node *lchild,*rchild;
Node(int V)
{
data=V;
lchild = NULL;
rchild = NULL;
}
};
class three
{
public:
struct Node *root;
three();
three(int V);
~three();
void input();//输入函数
void setthree(int father,int son);//构建函数
Node *found(Node *pNode,int X);
void preoder(Node *N);//前序遍历
void Inother(Node *N);//中序遍历
void postorder(Node *N);//后序遍历
void layoutput(Node *N,int k,int M);//输出同一层的所有元素
};
void three::layoutput(Node *N,int k,int M)
{
struct Node *tool;
if(N==NULL)
return ;
tool=N;
if(M==k)
{
cout<<N->data<<" ";
return ;
}
int I=M;
layoutput(tool->lchild,k,++I);
I=M;
layoutput(tool->rchild,k,++I);
return ;
}
void three::postorder(Node *N)
{
if(N==NULL)
return ;
postorder(N->lchild);
postorder(N->rchild);
cout<<N->data<<" ";
}
void three::Inother(Node *N)
{
if(N==NULL)
return ;
Inother(N->lchild);
cout<<N->data<<" ";
Inother(N->rchild);
}
void three::preoder(Node *N)
{
if(N==NULL)
return ;
cout<<N->data<<" ";
preoder(N->lchild);
preoder(N->rchild);
}
Node *three::found(Node *Node,int X)
{
if(Node==NULL)
return NULL;
if(Node->data==X)
return Node;
if(Node->lchild==NULL&&Node->rchild==NULL)
return NULL;
else
{
if(Node->lchild!=NULL)
{
struct Node *Temp=found(Node->lchild,X);
if(Temp!=NULL)
return Temp;
else
{
return found(Node->rchild,X);
}
}
else
return found(Node->rchild,X);
}
}
void three::setthree(int father,int son)
{
struct Node * tool, *tool2;
tool=found(root,father);
if(tool==NULL)
{
cout<<"erro"<<endl;
return ;
}
if(tool->lchild==NULL)
{
tool2=new Node(son);
tool->lchild=tool2;
}
else if(tool->rchild==NULL)
{
tool2=new Node(son);
tool->rchild=tool2;
}
else
{
cout<<"此节点已经拥有两个子节点"<<endl;
}
return ;
}
void three::input()
{
int a,b;
while(cin>>a>>b&&a&&b)
{
setthree(a,b);
}
return ;
}
three::three()
{
root=NULL;
}
three::three(int V)
{
root = new Node(V);
if(root==NULL)
return ;
}
int main()
{
three *U=new three(1);
U->input();
cout<<"前序遍历:"<<endl;
U->preoder(U->root);
cout<<endl;
cout<<"中序遍历:"<<endl;
U->Inother(U->root);
cout<<endl;
cout<<"后序遍历:"<<endl;
U->postorder(U->root);
cout<<endl;
int T;//层数
while(cin>>T)
{
//cin>>T;
U->layoutput(U->root,T,1);
cout<<endl;
}
system("pause");
return 0;
}
/*
1 2
1 3
2 4
2 5
4 8
4 9
5 10
5 11
3 6
3 7
*/
大概就先这样如果有关于树的全新操作,一定补上。