Mình đang học về cây nhị phân, trong quá trình học phát sinh bài toán này mong cao thủ giúp đỡ: Xuất ra cây theo hình dạng cây (theo hình dáng cây nha, chứ không phải theo hàng ngang), mình đã post bài hỏi bên manguon mà có vẻ chẳng ai chịu khó giúp, nên hôm nay cầu cứu bên gamevn ::(
Dùng phương pháp duyệt cây theo left - node - right đó bạn. Mã: #include<iostream.h> char s[8][80]; int x = 0; // khoang cach moi o so #define DISTANCE 3 struct Node { int info; Node *left, *right; Node(int n) { info = n; left = right = NULL; } Node() { left = right = NULL; } }; typedef Node* Tree; void Insert(Tree &T, int n) { if(T == NULL) { T = new Node(n); } else { if(n < T->info) { Insert(T->left, n); } else if(n > T->info) { Insert(T->right, n); } } } void number_to_string(int n, char* c) { int r = 0; while(n != 0) { r = n % 10; n /= 10; *c = '0' + r; c--; } } void LNR(Tree T, int level) { if(T != NULL) { LNR(T->left, level + 1); cout << T->info << " "; x++; char *c = &s[level][DISTANCE * x - 1]; number_to_string(T->info, c); LNR(T->right, level + 1); } } main() { Tree T = 0; int n; cout << "Enter -1 to quit: \n"; do { cout << "Insert: "; cin >> n; if(n == -1) break; Insert(T, n); } while(1); LNR(T, 0); cout << endl << "Tree : \n"; for(int i = 0; i < 8 ; i++) { for(int j = 0 ; j < 80 ; j++) cout << s[i][j]; cout << endl; } return 0; }