#include "stdio.h" #include<malloc.h> typedef struct BSTreeNode { int m_nValue; struct BSTreeNode *m_pLeft; struct BSTreeNode *m_pRight; }BSTreeNode,*BStd; BSTreeNode *pHead=NULL;//保存当前访问节点的前一个节点 BSTreeNode *pIndex=NULL;//保存当前访问节点的前一个节点 void TraverseBSTreeNode(BStd root) { if(root) { printf("%d",root->m_nValue); TraverseBSTreeNode(root->m_pLeft); TraverseBSTreeNode(root->m_pRight); } } void TraverseLinkedList() { int i; for(i=0;i<4;i++) { printf("%d",pHead->m_nValue); pHead=pHead->m_pRight; } } BStd insertBSTreeNode(BStd root,int value) { if(value<root->m_nValue) { if(root->m_pLeft==NULL){ BStd p=(BStd)malloc(sizeof(BSTreeNode)); p->m_pLeft=NULL; p->m_pRight=NULL; p->m_nValue=value; root->m_pLeft=p; }else insertBSTreeNode(root->m_pLeft,value); }else if(value>root->m_nValue){ if(root->m_pRight==NULL){ BStd p=(BStd)malloc(sizeof(BSTreeNode)); p->m_pLeft=NULL; p->m_pRight=NULL; p->m_nValue=value; root->m_pRight=p; }else insertBSTreeNode(root->m_pRight,value); }else{ printf("已经存在,不需要创建\n."); } return root; } //转化本质上就是树的中序遍历 void treeToLinkedList(BSTreeNode *bd) { if(bd==NULL) return ; if(bd->m_pLeft!=NULL) treeToLinkedList(bd->m_pLeft); bd->m_pLeft=pIndex;//将当前访问节点的左指针指向前一个节点 if(NULL==pIndex)//如果前一个节点是空,说明是第一次访问 pHead=bd;//此时的节点应作为双向链表的表头节点 else pIndex->m_pRight=bd; pIndex=bd; if(bd->m_pRight!=NULL) treeToLinkedList(bd->m_pRight); } int main() { //先创建了一个节点 BStd root=(BStd)malloc(sizeof(BSTreeNode)); root->m_pLeft=NULL; root->m_pRight=NULL; scanf("%d",&root->m_nValue); int i=0; int value; for(;i<3;i++) { scanf("%d",&value); printf("%d\n",value); root=insertBSTreeNode(root,value); // TraverseBSTreeNode(root); TraverseBSTreeNode(root); printf("\n"); // printf("%d\n",root->m_nValue); } treeToLinkedList(root); printf("\n"); TraverseLinkedList(); system("pause"); }