二叉排序樹一些操作
阿新 • • 發佈:2018-12-23
輸入若干個不同的正整數(以0結束),按順序建立一顆二叉排序樹,輸出中序遍歷結果。再輸入一個數X,在建好的二叉排序樹中查詢有無關鍵字X這個結點,有則刪除該節點,無則插入這個結點,刪除或插入後還要保證滿足二叉排序樹的要求。最後請用鄰接表的形式再次輸入該二叉排序樹。
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<queue> using namespace std; struct node { node* left; node*right; int val; }; node*root; void build(int k, struct node*&x) { if (x == NULL) { x = new struct node; x->left = NULL; x->right = NULL; x->val = k; } else { if (k < x->val) { build(k, x->left); } else { build(k, x->right); } } } void puts(struct node *x) { if (x != NULL) { puts(x->left); cout << x->val ; puts(x->right); } } void exers(node *&x) { if (x->left == NULL && x->right == NULL) { node *n = root; if (n->val == x->val) root = NULL; while (1) { if (n->left!=NULL&&n->left->val == x->val) { n->left = NULL; break; } if (n->right!=NULL&&n->right->val == x->val) { n->right = NULL; break; } if (x->val > n->val) { n = n->right; } else { n = n->left; } } } else { if (x->left != NULL && x->right != NULL) { node*n = x->left; while (1) { if (n->right == NULL) { n->right = x->right; break; } n = n->right; } x->right = x->left->right; x->val = x->left->val; x->left = x->left->left; } else { if (x->left != NULL) { x->right = x->left->right; x->val = x->left->val; x->left = x->left->left; } else { x->left = x->right->left; x->val = x->right->val; x->right = x->right->right; } } } } void finds(int x) { node*n = root; while (1) { if (n->val == x) { cout << "YES" << endl; exers(n); return; } if (x > n->val) n = n->right; else n = n->left; } } void print(node *x) { if (x == NULL) return; cout << x->val; if (x->left || x->right)cout << "("; if (x->left)print(x->left); if (x->right)cout << ","; if (x->right)print(x->right); if (x->left || x->right)cout << ")"; } int main() { int k; int X; while (1) { cin >> k; if (k == 0) break; build(k, root); } puts(root); cout << endl; cin >> X; finds(X); puts(root); cout << endl; print(root); return 0; }