我使用下面的程序进行先序建立二叉树和先序中序后序遍历,但是发现总是有问题,求帮助!!!!!
#include<iostream>usingnamespacestd;classTreeNode{public:chardata;TreeNode*L,*R;TreeN...
#include <iostream>
using namespace std;
class TreeNode
{
public:
char data;
TreeNode *L,*R;
TreeNode()
{
L = NULL;
R = NULL;
}
};
class Tree
{
public:
TreeNode *root;
Tree() {root = NULL;}
int Creat();
int Creat(TreeNode *p);
void PreOrder()
{
PreOrder(root);
}
void PreOrder(TreeNode *p);
void InOrder()
{
InOrder(root);
}
void InOrder(TreeNode *p);
void PastOrder()
{
PastOrder(root);
}
void PastOrder(TreeNode *p);
};
int Tree::Creat()
{
char ch;
scanf("%c",&ch);
if(ch == '#') root=NULL;
else
{
root = new TreeNode;
root->data = ch;
Creat(root->L);
Creat(root->R);
}
return 1;
}
int Tree::Creat(TreeNode *p)
{
char ch;
scanf("%c",&ch);
if(ch == '#')
{
p=NULL;
return 1;
}
p = new TreeNode;
p->data = ch;
Creat(p->L);
Creat(p->R);
return 1;
}
void Tree::PreOrder(TreeNode *p)
{
if(p != NULL)
{
cout << p->data << " ";
PreOrder(p->L);
PreOrder(p->R);
}
}
void Tree::InOrder(TreeNode *p)
{
if(p != NULL)
{
InOrder(p->L);
cout << p->data << " ";
InOrder(p->R);
}
}
void Tree::PastOrder(TreeNode *p)
{
if(p != NULL)
{
PastOrder(p->L);
PastOrder(p->R);
cout << p->data << " ";
}
}
int main()
{
Tree T;
T.Creat();
T.PreOrder();
T.InOrder();
T.PastOrder();
return 0;
}
这是测试用例
-+a##*b##c##/d##e##
求解答问什么无法建立一个树 展开
using namespace std;
class TreeNode
{
public:
char data;
TreeNode *L,*R;
TreeNode()
{
L = NULL;
R = NULL;
}
};
class Tree
{
public:
TreeNode *root;
Tree() {root = NULL;}
int Creat();
int Creat(TreeNode *p);
void PreOrder()
{
PreOrder(root);
}
void PreOrder(TreeNode *p);
void InOrder()
{
InOrder(root);
}
void InOrder(TreeNode *p);
void PastOrder()
{
PastOrder(root);
}
void PastOrder(TreeNode *p);
};
int Tree::Creat()
{
char ch;
scanf("%c",&ch);
if(ch == '#') root=NULL;
else
{
root = new TreeNode;
root->data = ch;
Creat(root->L);
Creat(root->R);
}
return 1;
}
int Tree::Creat(TreeNode *p)
{
char ch;
scanf("%c",&ch);
if(ch == '#')
{
p=NULL;
return 1;
}
p = new TreeNode;
p->data = ch;
Creat(p->L);
Creat(p->R);
return 1;
}
void Tree::PreOrder(TreeNode *p)
{
if(p != NULL)
{
cout << p->data << " ";
PreOrder(p->L);
PreOrder(p->R);
}
}
void Tree::InOrder(TreeNode *p)
{
if(p != NULL)
{
InOrder(p->L);
cout << p->data << " ";
InOrder(p->R);
}
}
void Tree::PastOrder(TreeNode *p)
{
if(p != NULL)
{
PastOrder(p->L);
PastOrder(p->R);
cout << p->data << " ";
}
}
int main()
{
Tree T;
T.Creat();
T.PreOrder();
T.InOrder();
T.PastOrder();
return 0;
}
这是测试用例
-+a##*b##c##/d##e##
求解答问什么无法建立一个树 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询