向大家请教下,树的插入问题,C语言描述
//功能描述:已经创建了一棵树,要插入一个新结点作为在这棵树的一个结点的左子树,这个结点,原来的左子树成了新插入的结点的左子树,代码如下,我想请教一下,我的代码为何达不到我的目的呢?
//--------------------------------------------------------
BinaryTree.h
//-----------------------------------------------------------
#include "stdlib.h"
#define MAX_TREE_SIZE 100
#define MAXSIZE 100
#ifndef Elem
#define Elem int
#endif
typedef struct BiTNode //树结点
{
Elem data;
struct BiTNode *lchild,*rchild;
}*TreeNode;
TreeNode CreateNode(Elem data) //创建树结点
{
TreeNode Node=(TreeNode)malloc(sizeof(struct BiTNode));
Node->data=data;
Node->lchild=NULL;
Node->rchild=NULL;
return Node;
}
TreeNode SearchNode(TreeNode root,Elem data) //查找一个树结点,data为所查找的结点的值
{
TreeNode &tp=root;
Queue Q=InitQueue();
if(tp==NULL)return NULL;
while(tp)
{
if(tp->data==data)return tp;
if(tp->lchild)Push(Q,tp->lchild);
if(tp->rchild)Push(Q,tp->rchild);
tp=Pop(Q);
}
return NULL;
}
void InsertNode(TreeNode &position,Elem data,int flag)//flag=0 insert left,flag=1 insert right
{
TreeNode temp=NULL;
if(flag==0){
if(position->lchild!=NULL){//不是叶子结点
temp=CreateNode(data);
temp->lchild=position->lchild;
position->lchild=temp;
}
else
position->lchild=CreateNode(data);
}
if(flag==1){
if(position->rchild!=NULL){//不是叶子结点
temp=CreateNode(data);
temp->rchild=position->rchild;
position->rchild=temp;
}
else
position->rchild=CreateNode(data);
}
}
void preorder(TreeNode root)//遍历
{
if(root == NULL) return;
visit(root);
preorder(root->lchild);
preorder(root->rchild);
}
//-------------------------------------------
#include "BinaryTree.h"
int main(int argc, char* argv[])
{
TreeNode root,position;
printf("create the binary tree!\n");
root=CreateNode(10);
root->lchild=CreateNode(20);
root->rchild=CreateNode(30);
root->lchild->lchild=CreateNode(40);
root->lchild->rchild=CreateNode(50);
root->rchild->lchild=CreateNode(60);
root->rchild->rchild=CreateNode(70);
root->lchild->lchild->lchild=CreateNode(80);
root->lchild->lchild->rchild=CreateNode(90);
position=SearchNode(root,40);
printf("insert the node!\n");
InsertNode(position,100,0);
printf("打印!\n");
preorder( root);
return 0;
}
呵,有点长,各位耐心看下了,谢谢你们