thachthen_it Admin
Tổng số bài gửi : 53 Reputation : 0 Join date : 19/05/2011 Age : 32 Đến từ : trà vinh
| Tiêu đề: nhập 1 mảng sắp xếp mảng tăng dần (dùng cây) Sun May 29, 2011 8:27 pm | |
| GIẢI THUẬT:trước tiên từ mảng đã cho ta tạo tìm cách chèn từng phần từ vào cây sao cho thõa tính chất cây nhị phân tìm kiếm BST( Binary Search Tree): duyệt cây theo Left-Node-Right ta được mảng tăng dần - Code:
-
#include<conio.h> #include<iostream.h> #include<alloc.h> #include<iomanip.h> struct node { int infor; struct node *left,*right; }; typedef node *Tree; Tree root; int InsertNode(Tree &root,int key); void Initialize_BST(Tree &root); int LNR(Tree root); main() { Initialize_BST(root); LNR(root); } int InsertNode(Tree &root,int key) { if(root!=NULL) { if(root->infor==key)//node da ton tai return 0; if(root->infor>key) return InsertNode(root->left,key); return InsertNode(root->right,key); } else { root=new node; //neu root==NULL cap phat bo nho cho node if(root->infor==NULL) return -1;//khong du bo nho cap phat root->infor=key; root->left=root->right=NULL; return 1;//cap phat thanh cong
} } void Initialize_BST(Tree &root) { int n,key; cout<<"nhap so luong node muon tao: ";cin>>n; for(int i=1;i<=n;i++) { cout<<"\tnode thu "<<i<<"= "; cin>>key; InsertNode(root,key); } } int LNR(Tree root) { if(root!=NULL) { LNR(root->left); cout<<setw(4)<<root->infor; LNR(root->right); return 1;//duyet thanh cong } return 0;//tra ve 0 khi root==NULL } | |
|