二叉查找树<链表实现>

来源:互联网 发布:c语言程序员工资 编辑:程序博客网 时间:2024/06/07 22:03

thinking:第一个结点作为根结点,然后接下来每个结点与根结点对比,如大于根结点则放右边,小于根结点则放左边,然后比较下一个结点,知道遇到空节点则储存、

输入样例:

9
6 3 8 5 2 9 4 7 10

输出样例:(前序遍历)

6 3 2 5 4 8 7 9 10

代码:

#include <stdlib.h>#include <iostream>using namespace std;struct tree{tree *left;tree *right;int data;};typedef struct tree *b_tree;b_tree insert(b_tree root,int node){b_tree parentnode;b_tree newnode;b_tree currentnode;newnode=(b_tree)malloc(sizeof(tree));newnode->data=node;newnode->right=NULL;newnode->left=NULL;if(root==NULL)return newnode;else{currentnode=root;while(currentnode!=NULL){parentnode=currentnode;if(currentnode->data>node)currentnode=currentnode->right;elsecurrentnode=currentnode->left;}if(parentnode->data>node)parentnode->right=newnode;elseparentnode->left=newnode;}return root;}b_tree creat(int *node,int len){b_tree root=NULL;for(int i=1;i<=len;i++)root=insert(root,node[i]);return root;}void print(b_tree root){if(root!=NULL){printf("%d ",root->data);print(root->right);print(root->left);}}int main(){freopen("in.txt","r",stdin);int i,n;cin >> n;b_tree root;int node[n+1];for(i=1;i<=n;i++)cin >> node[i];root=creat(node,n);print(root);return 0;} 


0 0