创建二叉树:输入0结束
void CreateTree(BinaryTree **pTree) { //输入数值 int nNum; scanf("%d",&nNum); if(nNum == 0)return; *pTree = (BinaryTree*)malloc(sizeof(BinaryTree)); (*pTree)->nValue = nNum; (*pTree)->pLeft = NULL; (*pTree)->pRight = NULL; //左 CreateTree(&((*pTree)->pLeft)); //右 CreateTree(&((*pTree)->pRight)); }
创建二叉树:输入#结束,需要注意的是%c读入空格和换行,所以输入的时候要一连串输入,
void CreateTree(Tree** tmp) { char num = 0; scanf("%c",&num); if(num == '#') return; *tmp = (Tree*)malloc(sizeof(Tree)); (*tmp)->val = num - '0'; (*tmp)->pleft = NULL; (*tmp)->pright = NULL; CreateTree(&((*tmp)->pleft)); CreateTree(&((*tmp)->pright)); }
测试数据:124##5##36###
前序输出结果为:124536
函数为前序插入,只能为前序插入。因为必须确定根才能,建立左孩子和右孩子
将数组元素作为前序遍历的结果建立二叉树:
根从0开始,第2*i+1个节点为它的左孩子,2*i+2为它的右孩子
Tree* Create(int* arr,int len) { if(arr == NULL || len == 0) return NULL; Tree* tree = (Tree*)malloc(sizeof(Tree)*len); for(int i = 0; i < len; i++) { tree[i].val = arr[i]; if((2*i+1) < len) tree[i].pleft = &tree[2*i+1]; else (tree[i]).pleft = NULL; if((2*i+2) < len) tree[i].pright = &tree[2*i+2]; else tree[i].pright = NULL; } return tree; }