您的位置:首页 > 其它

二叉树的创建和遍历、删除

2017-10-16 08:29 197 查看
#include <stdio.h>
#include <malloc.h>

typedef struct  BinaryTreeNode
{
struct BinaryTreeNode *pLeft;
struct BinaryTreeNode *pRight;
int mValue;
}BINARYTREENODE;

void CreateBinaryTree(BinaryTreeNode **pRoot)
{
int value = 0;
printf("Please Input a None Zero Value : ");
scanf("%d",&value);
printf("Value = %d\n",value);
if(value == 0)
{
*pRoot = NULL;
return;
}
else
{
*pRoot = (BINARYTREENODE *)malloc(sizeof(BINARYTREENODE));
printf("*pRoot = %x\n",*pRoot);
printf("*pRoot = %x\n",pRoot);
(*pRoot)->mValue = value;
CreateBinaryTree(&((*pRoot)->pLeft));
CreateBinaryTree(&((*pRoot)->pRight));
}
}

void DeleteBinaryTree(BINARYTREENODE ** pRoot)
{
if ((*pRoot)->pLeft == NULL && (*pRoot)->pRight == NULL)
{
printf("Delete Node is %d\n",(*pRoot)->mValue);
*pRoot = NULL;
free(*pRoot);
return;
}
else
{
DeleteBinaryTree(&((*pRoot)->pLeft));
DeleteBinaryTree(&((*pRoot)->pRight));
}
}
void ShowBinaryTree(BINARYTREENODE * pRoot)
{
if (NULL!=pRoot)
{
printf("%d ",pRoot->mValue);
}
}

void PerOrder(BINARYTREENODE * pRoot)
{
if (NULL!=pRoot)
{
ShowBinaryTree(pRoot);
PerOrder(pRoot->pLeft);
PerOrder(pRoot->pRight);
}
}

void InOrder(BINARYTREENODE * pRoot)
{
if (NULL!=pRoot)
{
InOrder(pRoot->pLeft);
ShowBinaryTree(pRoot);
InOrder(pRoot->pRight);
}
}

void PostOrder(BINARYTREENODE * pRoot)
{
if (NULL!=pRoot)
{
PostOrder(pRoot->pLeft);
PostOrder(pRoot->pRight);
ShowBinaryTree(pRoot);
}
}

int main()
{
BINARYTREENODE * pRoot = NULL;

CreateBinaryTree(&pRoot);
printf("%x\n",pRoot);
printf("Find All Pre Order of Binary Tree : ");
PerOrder(pRoot);
printf("\n");

printf("Find All In Order of Binary Tree : ");
InOrder(pRoot);
printf("\n");

printf("Find All Post Order of Binary Tree : ");
PostOrder(pRoot);
printf("\n");

printf("Before Delete %x\n",pRoot);
while (pRoot!=NULL)
{
DeleteBinaryTree(&pRoot);
}

printf("After Delete %x\n",pRoot);
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐