c++先序构建二叉树

2025-02-26 15:04:37
推荐回答(1个)
回答1:

#include
using namespace std;
struct node{
int data;
node *lchild;
node *rchild;
};
class tree{
private:
int k;
node *root;
node *current;
public:
tree(){
root=NULL;
current=root;
k=0;
}
void creat_tree(node **t);//这是用指针的方法来实现的。所以修改了一下参数形式。
void display1() {Preorder(root); cout< void display2(){inorder(root); cout< void display3() {Postorder(root); cout< void pre_creattree(){creat_tree(¤t); cout< void Preorder(node *temp);//先序遍历
void inorder(node *temp);//中序遍历
void Postorder(node *temp);//后序遍历
};
void tree::creat_tree(node **t){//先序建立一棵二叉树,采用递归形式建立
int i=0;
cin>>i;
if(i!=0){
node *h=new node;//新建节点
h->data=i;
*t=h;
if(k==0)//如果是根节点
root=*t;
k++;
creat_tree(&(*t)->lchild);//参数做了相应改变
creat_tree(&(*t)->rchild);//参数做了相应改变
}
else //i=0时为空节点
*t=NULL;
}
void tree::Preorder(node *temp){ //这是先序遍历二叉树,采用了递归的方法。
if(temp!=NULL){
cout<data<<" ";
Preorder(temp->lchild);
Preorder(temp->rchild);
}
}
void tree::inorder(node *temp){ //这是中序遍历二叉树,采用了递归的方法。
if(temp!=NULL){
inorder(temp->lchild);
cout<data<<" ";
inorder(temp->rchild);
}
}
void tree::Postorder(node *temp){ //这是后序遍历二叉树,采用了递归的方法。
if(temp!=NULL){
Postorder(temp->lchild);
Postorder(temp->rchild);
cout<data<<" ";
}
}
void main(){
tree A;
cout<<"input"< A.pre_creattree();
cout< A.display1();
cout< A.display2();
cout< A.display3();
}