创建2叉树与讲左右子数互换

来源:百度知道 编辑:UC知道 时间:2024/09/23 05:22:38
二、实验内容及要求:
1、建立一棵6个结点的二叉树,结点的数据值是正整数,并按前序输出之;
2、完成对以上二叉树中所有结点的左、右子树相互交换,并按中序输出交换以后的结果。
3、编程统计二叉树的叶结点的数目。
我的程序是这样的。希望高手帮我改下哈。在创建2叉树的时候用递归程序好像无限循环了,画面都是要求输入数据的。
#include "stdio.h"
#include <malloc.h>
#include <stdlib.h>

typedef struct node *tree_pointer;
typedef struct node{
int date;
tree_pointer left_child,right_child;
};
tree_pointer ptr=NULL;

int count=0;
void CreateTree(tree_pointer *p)
{
int num;

scanf("%d", &num);

if(num==0)
{
*p = NULL;
}
else
{
if(!((*p) = (tree_pointer)malloc(sizeof(tree_pointer))))
{
exit(1);
}

CreateTree(&((*p)->left_child));
(*p)->date =num;
CreateTree(&((*p)->right_child));

}
}

你的递归函数缺少基本条件

不定义为static还是会不断要求你输入
static int num;

if(num==-1) return; //一定要先判断停止条件再用scanf输入

scanf("%d", &num);

void change_left_right(tree_pointer *p)
{
tree_pointer item;
if (*p) { //应该判断孩子结点*p是否为空,而不是其地址
change_left_right(&((*p)->left_child));
change_left_right(&((*p)->right_child));
item=(*p)->left_child;
(*p)->left_child=(*p)->right_child;
(*p)->right_child=item;

}
}

我使用C++实现了上述的1,2问题,只是数据是char型,不过可以使用typedef更改,我们可以交流下