数据结构学习---二叉树简单实现
想必二叉树大家都很熟悉。结点有左右孩子,二叉树非常使用,编写二叉树和链表差不多,多多运用迭代就能很好的解决问题,但是这仅仅限于在量比较小的情况下,非递归的代码执行效率大家有目共睹。
#ifndef _TREENODE_H_
#define _TREENODE_H_
typedef int Elemtype;
typedef struct treeNode{
Elemtype tRoot;
struct treeNode * pLight;
struct treeNode * pRight;
}treeNode;
#endif
定义结构体还是差不多的。
#include<stdio.h>
#include"treeNode.h"
void show(treeNode * pNode)
{
if(NULL == pNode)
return;
printf("%d - ",pNode->tRoot);
show(pNode->pLight);
show(pNode->pRight);
}
先根,中根,后根就是把printf放到不同的位置。
/*************************************************************************
> File Name: InitHead.c
> Author: aaron
> Mail: 60360329@163.com
> Created Time: Fri 17 Mar 2017 04:33:21 PM CST
************************************************************************/
#include<stdio.h>
#include"treeNode.h"
#include<string.h>
#include<stdlib.h>
treeNode * InitHead(Elemtype data)
{
treeNode * pNode = (treeNode *)malloc(sizeof(treeNode));
if (NULL != pNode)
{
pNode->tRoot = data;
pNode->pLight = NULL;
pNode->pRight = NULL;
}
return pNode;
}
初始化头结点。最好的写在一起的还有带销毁的。
/*************************************************************************
> File Name: createTree.c
> Author: aaron
> Mail: 60360329@163.com
> Created Time: Fri 17 Mar 2017 03:05:37 PM CST
************************************************************************/
#include<stdio.h>
#include"treeNode.h"
#include<stdlib.h>
#include"Fun.h"
treeNode * recursion(treeNode * pNode,Elemtype * INdata)
{
if (NULL == pNode)
{
treeNode * qtmp = InitHead(*INdata);
return qtmp;
}
else if (*INdata > pNode->tRoot)
{
pNode->pLight = recursion(pNode->pLight,INdata);
return pNode; //起先这里没加
}
else
{
pNode->pRight = recursion(pNode->pRight,INdata);
return pNode; //这里同样
}
}
treeNode * createTree(treeNode * pNode,Elemtype * INdata)
{
if (NULL == pNode
||NULL == INdata)
{
return pNode;
}
recursion(pNode,INdata);
return pNode;
}
(二叉排序树)这里我碰到了一个我自己看了好久的问题。上面有地方没加return 只有一个函数出口,导致递归的时候超过三个结点插入的时候,只能插在不超过三个三层的位置。后来我看了一下,递归了好几层都只有在第一层这个出口这里,所以解决问题的方法是在每次调用递归函数的时候加出口。
-----------------后补上非递归二叉排序树。2017-03-1911:42:19
浙公网安备 33010602011771号