二叉树:二叉树的每个结点至多只有二棵子树(不存在度大于2的结点),二叉树的子树有左右之分,次序不能颠倒。
采用先序且递归创建二叉树。
二叉树结点表示如下
typedef char BTDataType;
typedef struct BinaryTreeNode
{
BTDataType data;
struct BinaryTreeNode *left;
struct BinaryTreeNode *right;
}BTNode, *PBTNode;
完整代码
int main()
{
char array[] = "ABD###CE##F";
int size = strlen(array);
CreateBinaryTree(&proot, array, size, '#');
return 0;
}
PBTNode BuyNode(BTDataType a)
{
PBTNode pNew = (PBTNode)malloc(sizeof(BTNode));
assert(pNew);
pNew->data = a;
pNew->left = NULL;
pNew->right = NULL;
return pNew;
}
void CreateBinaryTree(PBTNode *proot, BTDataType array[], int size, BTDataType c)
{
int index = 0;
assert(proot && array);
_CreateBinaryTree(proot, array, &index, size, c);
}
void _CreateBinaryTree(PBTNode *proot, BTDataType array[],int *index, int size, BTDataType c)
{
if (*index<size && array[*index]!=c) //ABD###CE##F
{
//创建根结点
*proot = BuyNode(array[*index]);
++(*index);
//创建左子树
_CreateBinaryTree(&(*proot)->left, array, index, size, c);
++(*index);
//创建右子树
_CreateBinaryTree(&(*proot)->right, array, index, size, c);
}
}