- #include <stdio.h>
- #include <stdlib.h>
- struct tree
- {
- int data;
- struct tree *left;
- struct tree *right;
- };
- typedef struct tree treenode;
- typedef treenode *btree;
- /*
- 往链表二叉树插入数据
- */
- btree insertnode(btree root, int val)
- {
- btree newnode;
- btree current;
- btree backnode;
- newnode = (btree)malloc(sizeof(treenode));
- newnode->data = val;
- newnode->right = NULL;
- newnode->left = NULL;
- if(root == NULL)
- {
- return newnode;
- }else{
- current = root;
- while(current != NULL)
- {
- backnode = current;
- if(val > current->data)
- current = current->right;
- else
- current = current->left;
- }
- if(backnode->data > val)
- backnode->left = newnode;
- else
- backnode->right = newnode;
- }
- return root;
- }
- //创建链表的二叉树
- btree create_sbtree(int *data, int len)
- {
- int i;
- btree root = NULL;
- for(i=0;i<len;i++)
- {
- printf("%d\\t",data[i]);
- root = insertnode(root,data[i]);
- }
- return root;
- }
- void printbtree(btree root)
- {
- btree ptr;
- printf("\\nroot is :%d\\n",root->data);
- ptr = root->left;
- printf("输出左子树:\\n");
- while(ptr)
- {
- printf("%d\\n",ptr->data);
- if(ptr->right)
- {
- printf("%d\\n",ptr->right->data);
- }
- ptr = ptr->left;
- }
- ptr = root->right;
- printf("输出右子树:\\n");
- while(ptr)
- {
- printf("%d\\n",ptr->data);
- if(ptr->left)
- {
- printf("%d\\n",ptr->left->data);
- }
- ptr = ptr->right;
- }
- }
- /*
- * 中序遍历
- */
- void inorder(btree b)
- {
- if(b !=NULL)
- {
- inorder(b->left);
- printf("%d,",b->data);
- inorder(b->right);
- }
- }
- /*
- * 前序遍历
- */
- void preorder(btree b)
- {
- if(b !=NULL)
- {
- printf("%d,",b->data);
- preorder(b->left);
- preorder(b->right);
- }
- }
- /*
- * 后序遍历
- */
- void postorder(btree b)
- {
- if(b !=NULL)
- {
- postorder(b->left);
- postorder(b->right);
- printf("%d,",b->data);
- }
- }
- void main()
- {
- int data[10] = {5,6,4,8,2,3,7,1,9};
- //create a bree
- btree root = NULL;
- int i;
- root =create_sbtree(data,9);
- printbtree(root);
- printf("中序遍历:\\n");
- inorder(root);
- printf("\\n");
- printf("前序遍历\\n");
- preorder(root);
- printf("\\n");
- printf("后序遍历\\n");
- postorder(root);
- printf("\\n");
- }
- //该片段来自于http://www.codesnippet.cn/detail/3010201410853.html
来源: http://www.codesnippet.cn/detail/3010201410853.html