...错误比较多
说说比较明显的:
1.二叉树先序遍历
void preorder(tree *t)//二叉树先序遍历
{
if(t)
{
cout<
}
else
{
preorder(t->lchild);
preorder(t->rchild);
}
}
这个是遍历不起来的,先序遍历是先根再左右子树,这个顺序是必须的,不是你程序中写的if..else..的有条件的遍历。
2.用先序建立二叉树
我明白你程序中的意思是想用递归方式来由根到左右子树来构成一个二叉树,但是这样得到的树是不确定的;一般通过先序序列确定一个二叉树是需要一个中序序列的,只靠一个先序序列二叉树是不能确定的。
3.还要说说关于new的使用
在你用先序构建二叉树的方法中,参数是tree *t,在其中
t=new tree;
t->data=c;
你好像是在动态申请一个struct tree类型的结构空间时,只对结构中的data域进行了赋值,而没有对左右孩子两个指针域赋值,而下面却以这两指针为参数递归调用左右孩子,虽然你的程序中没有发生访存错误,但是这种操作是很危险的,所以动态申请的时候要格外小心啊。
写程序就要多练,练后再看书时会发现书上的方法还真是好啊
我可以帮助你,你先设置我最佳答案后,我百度Hii教你。
#include "iostream.h"
struct treenode
{
int data;
treenode *lch,*rch;
};
class tree
{
public:
treenode *root;
public:
tree()
{
root=NULL;
}
void insert(treenode **p,int num);
treenode *search(treenode *p,int x);
void inorder(treenode *p);
void preorder(treenode *p);
void postorder(treenode *p);
void deletenode(treenode *p);
};
void tree::insert(treenode **p,int num)
{
treenode* p_node;
if (*p == NULL)
{
p_node=new treenode;
p_node->data=num;
p_node->lch=NULL;
p_node->rch=NULL;
*p = p_node;
}
else if (*p!=NULL)
{
p_node = *p;
if (num < p_node->data)
{
insert(&(p_node->lch),num);
}
if (num > p_node->data)
{
insert(&(p_node->rch),num);
}
}
}
void tree::inorder(treenode *p)
{
if (p!=NULL)
{
inorder(p->lch);
cout<
inorder(p->rch);
}
}
void tree::preorder(treenode *p)
{
if (p!=NULL)
{
cout<
preorder(p->lch);
preorder(p->rch);
}
}
void tree::postorder(treenode *p)
{
if (p!=NULL)
{
postorder(p->lch);
postorder(p->rch);
cout<
}
}
treenode* tree::search(treenode *p,int x)
{
if (p == NULL)
{
cout<
}
else if (p!=NULL)
{
if (x == p->data)
{
cout<
}
else if (x
return search(p->lch,x);
else if (x>p->data)
return search(p->rch,x);
}
return NULL;//
}
void tree::deletenode(treenode *p)
{
if (p->lch != NULL)
deletenode(p->lch);
if (p->rch != NULL)
deletenode(p->rch);
delete p;
p=NULL;
}
void main()
{
int number; //要查找的数
treenode *tempptr;
int array[10]={8,4,11,3,5,7,12,2,6,9};
tree binarytree;
for (int i=0;i<10;i++)
{
binarytree.insert(&binarytree.root,array[i]);
}
cout<<"*******************************"<
cout<
cout<
cout<
cin>>number;
tempptr=binarytree.search(binarytree.root,number);
cout<
if (tempptr!=NULL)
{
binarytree.deletenode(tempptr);
binarytree.inorder(binarytree.root);
}
}
你使用了迭代,所以在某些if语句分支没有返回一个指针,不过不影响。