今天想起写写二叉树,发现自己好久没有看这个然后秀逗了,这里涉及到的是值传递和地址传递的问题
#include <iostream>
using namespace std;
#include <stdlib.h>
typedef struct BTNode{
int data;
BTNode *pLChild,*pRChild;
}BTNode;
//创建2叉树
void CreateBTTree(BTNode*pTreeNode)
{
int input;
cout<<"等待输入"<<endl;
scanf("%d",&input);
if(input==0)
pTreeNode=NULL;
else
{
pTreeNode=new BTNode;
pTreeNode->data=input;
cout<<pTreeNode->data<<endl;
CreateBTTree(pTreeNode->pLChild);
CreateBTTree(pTreeNode->pRChild);
}
}
//先序遍历二叉树
void XianXuBianLi(BTNode*pTreeNode)
{
if(pTreeNode==NULL)cout<<"0"<<endl;
else
{
cout<<pTreeNode->data<<endl;
XianXuBianLi(pTreeNode->pLChild);
XianXuBianLi(pTreeNode->pRChild);
}
}
int main()
{
BTNode*pTree=NULL;
CreateBTTree(pTree);
XianXuBianLi(pTree);
return 0;
}
然后输入没有问题,看遍历的时候老是读内存出错,难道我new 的BTNode没有用
于是想了想,这个问题和值传递和地址传递是不是很像呢,我们来写一个类比一下
void Create(int a) { a=5; } int main() { int b=7; Create(b); cout<<"a's value is "<<b<<endl; }
这里的运行结果是a为7 值传递当然不改变他的值啦
现在我们改一下
void Create(int &a) { a=5; } int main() { int b=7; Create(b); cout<<"a's value is "<<b<<endl; }
好了,现在他的值可以改变了
同样如此在上面的二叉树创建的过程也是一样,传了一个指针进去了,这里应该传指针的引用,因为需要对指针的值进行修改
所以应该改为这样
//创建2叉树 void CreateBTTree(BTNode*&pTreeNode) { int input; cout<<"等待输入"<<endl; scanf("%d",&input); if(input==0) pTreeNode=NULL; else { pTreeNode=new BTNode; pTreeNode->data=input; cout<<pTreeNode->data<<endl; CreateBTTree(pTreeNode->pLChild); CreateBTTree(pTreeNode->pRChild); } }
这样就可以了,好久不写代码,很多东西理论和实践还是要结合在一起呀~~~