1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
| #include<iostream>
using namespace std;
typedef struct BiNode { int data; struct BiNode* lc; struct BiNode* rc; }BiNode, *BiTree;
bool EQ(int key1, int key2) { if(key1 == key2) return true; else return false; }
bool LT(int key1, int key2) { if(key1 < key2) return true; else return false; }
bool SearchBST(BiTree T, int key, BiTree f, BiTree &p) { if(!T) { p = f; return false; } else if(EQ(key, T->data)) { p = T; return true; } else if(LT(key, T->data)) { return SearchBST(T->lc, key, T, p); } else return SearchBST(T->rc, key, T, p); }
bool InsertBST(BiTree &T, int key) { BiTree p; if(!SearchBST(T, key, NULL, p)) { BiTree s = (BiTree)malloc(sizeof(BiNode)); s->data = key; s->lc = NULL; s->rc = NULL; if(!p) T = s; else if(LT(key, p->data)) p->lc = s; else p->rc = s; return true; } else return false; }
bool Delete(BiTree &p) { BiTree q; if(!p->rc) { q = p; p = p->lc; free(q); } else if(!p->lc) { q = p; p = p->rc; free(q); } else { q = p; BiTree s = p->lc; while(s->rc) { q = s; s = s->rc; } p->data = s->data; if(q != p) q->rc = s->lc; else q->lc = s->lc; free(s); } return true; }
bool DeleteBST(BiTree &T, int key) { if(!T) return false; else { if(EQ(key, T->data)) return Delete(T); else if(LT(key, T->data)) return DeleteBST(T->lc, key); else return DeleteBST(T->rc, key); } }
void OnOrder(BiTree T, int l, int r, int cen, int fa) { if(T) { OnOrder(T->lc, 1, 0, cen + 1, T->data); if(fa == -1) cout << "根节点" << " 该点为:" << T->data << " 层数为:" << cen << endl; else { if(l) cout << "该点为:" << T->data << " 该节点为 " << fa << " 的左儿子" << " 层数为:" << cen << endl; if(r) cout << "该点为:" << T->data << " 该节点为 " << fa << " 的右儿子" << " 层数为:" << cen << endl; } OnOrder(T->rc, 0, 1, cen + 1, T->data); } }
int main() { BiTree T; T = NULL; int n; cout << "请输入要插入的结点数:" << endl; cin >> n; cout << "依次输入每个结点的data, 空格分开" << endl; for(int i = 0;i < n;i++) { int x; cin >> x; InsertBST(T, x); } BiTree p = NULL; int x; cout << "输入查找的data:" << endl; cin >> x; if(SearchBST(T, x, NULL, p)) cout << "找见了"; else cout << "没找见"; cout << endl; cout << "输入删除的点:" << endl; cin >> x; if(DeleteBST(T, x)) cout << "删除了" << x; else cout << "没有" << x << "怎么删除啊?"; cout << endl; cout << endl << "这是这棵树:" << endl; OnOrder(T, 0, 0, 1, -1); return 0; }
|