《算法导论》12、二叉查找树(C++实现)
2015-05-27 15:37
686 查看
没啥好说的,都是书上的功能。
#include <iostream> #include "stdio.h" using namespace std; struct Node { Node *p; int value; Node *left; Node *right; }; Node* root; void inorderTreeWalk(Node* n) { if (n != NULL) { inorderTreeWalk(n->left); cout << n->value << " "; inorderTreeWalk(n->right); } } Node* treeSearch(Node* n, int value) { if (n == NULL || n->value == value) return n; else { if (n->value > value) return treeSearch(n->left, value); else return treeSearch(n->right, value); } } Node* treeMin(Node* n) { Node* r=n; while (r->left!=NULL) { r = r->left; } return r; } Node* treeMax(Node* n) { Node* r = n; while (r->right != NULL) { r = r->right; } return r; } Node* treeSuccessor(Node* n) { Node* x = n; if (n->right != NULL) return treeMin(n->right); Node* y = n->p; while (y != NULL && x == y->right) { x = y; y = y->p; } return y; } Node* treePredecessor(Node* n) { Node* x = n; if (n->left != NULL) return treeMax(n->left); Node* y = n->p; while (y != NULL && x == y->left) { x = y; y = y->p; } return y; } Node* treeInsert(Node* n, int key) { Node* y = NULL; Node* x = n; if (x == NULL) { x = new Node; x->p = NULL; x->value = key; x->left = NULL; x->right = NULL; root = x; return x; } while (x != NULL) { y = x; if (x->value > key) x = x->left; else x = x->right; } x = new Node; x->p = y; x->value = key; x->left = NULL; x->right = NULL; if (y != NULL) { if (key < y->value) y->left = x; else y->right = x; } return x; } void treeDelete(Node* n, Node* z) { Node* x, * y; if (z->left == NULL || z->right == NULL) y = z; else y = treeSuccessor(z); if (y->left != NULL) x = y->left; else x = y->right; if (x != NULL) x->p = y->p; if (y->p == NULL) root=x; else if (y == y->p->left) y->p->left = x; else y->p->right = x; if (y != z) z->value = y->value; delete y; } void treeDestroy(Node* n) { if (n != NULL) { treeDestroy(n->left); treeDestroy(n->right); delete n; } } void main() { int n = 10; //排序元素长度 for (int i = 0; i <n; i++) { treeInsert(root, rand() % 1000); } inorderTreeWalk(root); //中序遍历 cout << endl; Node* p = treeSearch(root, 962); if (p != NULL) { cout << "结果:" << p->value << endl; treeDelete(root, p); //删除节点 } else cout << "无该节点" << endl; inorderTreeWalk(root); //中序遍历 cout << endl; treeDestroy(root); system("pause"); }
相关文章推荐
- 算法导论--二叉查找树--C++实现
- 算法导论第十二章——二叉查找树的C++代码实现
- 算法导论中十二章C++实现二叉查找树建立,插入,删除,遍历操作
- 算法导论(c++实现)chapter4
- 《算法导论》中求最大子数组的C++实现
- 二叉查找树详解及C++实现
- C++模板实现二叉查找树(四 广度优先遍历)
- C++学习笔记(四)指针实现的链表、堆栈、队列、二叉查找树
- 设计模式C++实现(12)——备忘录模式
- 设计模式C++实现(12)——备忘录模式
- 最优二叉查找树-optimal-BST--C++实现2
- 设计模式C++实现(12)——备忘录模式
- 算法导论 插入排序 C++实现
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 设计模式C++实现(12)——备忘录模式2
- 二叉查找树的各种操作C++实现
- 二叉查找树(二叉排序树)操作大全C++实现
- C++模板实现二叉查找树(二 节点删除)
- 算法导论第十三章习题13-3——AVL树(高度平衡树)C++代码详细实现
- C++模板实现二叉查找树(三 深度优先遍历)