终于进入了二叉树的学习章节,二叉树的存储结构包括数组存储和链表存储,我主要介绍链表存储,数组存储也是类似的。
#include #include typedef struct tree{ int data; struct tree *left; struct tree *right;}*pnode,node;pnode createbinary(int a[],int n,pnode p);pnode insertNode(int data,pnode root);void print(pnode root);void main(){ int a[9] = { 6,3,8,5,2,9,4,7,11}; pnode root = NULL; root = createbinary(a,9,root); print(root); free(root);}pnode createbinary(int a[],int n,pnode root)//数组的值插入到链表中{ for(int i=0; i data = value; newnode->left = NULL; newnode->right = NULL; if(root == NULL)//第一插入 { root = newnode; } else { currentnode = root; while(currentnode != NULL)//currentnode为最后那个子节点,这个循环负责找到插入的位置 { parentnode = currentnode;//parentnode为最后那个子节点的父节点 if(currentnode->data > value) currentnode = currentnode->left; else currentnode = currentnode->right; } if(parentnode->data > value)//这个负责在找到的位置插入节点 { parentnode->left = newnode; } else { parentnode->right = newnode; } } return root;}void print(pnode root)//后序遍历{ if(root != NULL) { print(root->left); print(root->right); printf("%d\t",root->data); }}