cây nhị phân part1

#include<iostream> using namespace std; // 5 bước cơ bản khi thao tác với cây nhị phân //1. khai báo 1node //2. khởi tạo 1 tree //3. thêm 1 vào cây //4. tạo cây //5.duyệt cây // khai báo 1 node tren cây struct node { int data; struct node *pleft; struct node *pright; }; typedef node* tree; void init(tree &t) { t = NULL; } // thêm 1 phần tử vào cây void insert(tree &t, int x) { if (t == NULL) { node *p = new node; p->data = x; p->pleft = p->pright = NULL; t = p; } else { if (t->data > x) { insert(t->pleft, x); } else if(t->data<x) { insert(t->pright, x); } } } void createtree(tree &t)// tạo cây { init(t); int luachon; do { cout << "\n------------------"; cout << "\n1.Nhap gia tri x: "; cout << "\n0.Thoat-----------"; cout << "\nNhap lua chon: "; cin >> luachon; if (luachon == 1) { int x; cout << "\nNhap[ gia tri x: "; cin >> x; insert(t, x);// thêm x vào cây } } while (luachon != 0); } // duyệ cây void nlr(tree t) // node , left, right { if (t != NULL) { cout << t->data << " "; nlr(t->pleft); nlr(t->pright); } } void nrl(tree t) { if (t != NULL) { cout << t->data << " "; nrl(t->pright); nrl(t->pleft); } } void lnr(tree t ) { if (t != NULL) { lnr(t->pleft); cout << t->data << " "; lnr(t->pright); } } void lrn(tree t ) { if (t != NULL) { lrn(t->pright); lrn(t->pleft); cout << t->data << " "; } } void rnl(tree t) { if(t!=NULL) { rnl(t->pright); cout << t->data << " "; rnl(t->pleft); } } void rln(tree t) { if (t != NULL) { rln(t->pright); rln(t->pleft); cout << t->data << " "; } } int main() { tree t; createtree(t); cout << "\nnlr:"; nlr(t); cout << "\nnrl:"; nrl(t); cout << "\nlnr:"; lnr(t); cout << "\nlrn:"; lrn(t); cout << "\nrnl:"; rnl(t); cout << "\nrln:"; rln(t); cout << endl; system("pause"); return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.