二叉搜索树
#include<iostream> using namespace std; typedef struct Node { Node* left; Node* right; Node* p; int data; Node(){} Node(int dat) :data(dat){ left = right = NULL; } }BT; struct T { BT *root; T(){ root = NULL; } }; void Tree_Insert(T &tr, Node *z) { Node* y = NULL; Node* x = tr.root; while (x != NULL) { y = x; if (z->data < x->data) { x = x->left; } else x = x->right; } z->p = y; if (y == NULL) tr.root = z; else if (z->data < y->data) y->left = z; else y->right = z; } void Inorder_Tree_Walk(Node*x) { if (x != NULL) { Inorder_Tree_Walk(x->left); cout << x->data << " "; Inorder_Tree_Walk(x->right); } } Node* Tree_Search(Node*x, int k) { if((NULL==x)|| (k == x->data)) return x; if (k < x->data) { return Tree_Search(x->left, k); } else return Tree_Search(x->right,k); } Node*Iterative_Tree_Search(Node*x, int k) { while ((x != NULL) || (k != x->data)) { if (k < x->data) x = x->left; else x = x->right; } return x; } Node*Tree_Minimun(Node*x) { while (x->left != NULL) x = x->left; return x; } Node*Tree_Maxinum(Node*x) { while (x->right!=NULL) x = x->right; return x; } void Transplant(T&tr, Node*u, Node*v) { if (u->p == NULL) tr.root = v; else if (u == u->p->left) u->p->left = v; else u->p->right = v; if (v != NULL) v->p = u->p; } void Tree_Delete(T&tr, Node*z) { if (z->left == NULL) Transplant(tr, z, z->right); else if (z->right == NULL) Transplant(tr,z,z->left); else { Node*y = Tree_Minimun(z->right); if (y->p != z) { Transplant(tr,y,y->right); y->right = z->right; y->right->p = y; } Transplant(tr,z,y); y->left = z->left; y->left->p = y; } } int main() { T t; Node *n1 = new Node(1); Node *n2 = new Node(3); Node *n3 = new Node(2); Tree_Insert(t,n1); Tree_Insert(t,n2); Tree_Insert(t,n3); Inorder_Tree_Walk(t.root); cout << "\n"; Node*s=Tree_Search(t.root,3); cout << s->data << endl; Node*min = Tree_Minimun(t.root); cout <<"min:\t"<< min->data << endl; Node*max = Tree_Maxinum(t.root); cout << "max:\t" << max->data << endl; Tree_Delete(t,n3); Tree_Delete(t, n1); Inorder_Tree_Walk(t.root); cout << "\n"; }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!