BST 삽입 + 임의의 노드 삭제 귀속 실현

1955 단어 기타작은 지식
주로 bst에서 임의의 노드를 삭제합니다.
중차순 후계 노드를 찾아 연결을 완성합니다.
 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 2e5+32;
#define LL long long
const int inf = 0x3f3f3f3f;



class bst
{
public:
	struct node
	{
		int key;
		node *left;
		node *right;
		node(int k):key(k),left(nullptr),right(nullptr){}
	};

	node *head=nullptr;

	void insert(node *now,int key)
	{
		if(head==nullptr){
			node *temp=new node(key);
			head=temp;
			return;
		}
		if(key>now->key){
			if(now->right==nullptr){
				node *temp=new node(key);
				now->right=temp;
				return;
			}
			insert(now->right,key);
		}
		else if(key==now->key)
			return;
		else{
			if(now->left==nullptr){
				node *temp=new node(key);
				now->left=temp;
				return;
			}
			insert(now->left,key);
		}
	}
	void midout(node *now)// 
	{
		if(now!=nullptr){
			midout(now->left);
			printf("%d
",now->key); midout(now->right); } } node* findmin(node *now) { return now->left==nullptr?now:findmin(now->left); } node* deletemin(node *now) { if(now->left==nullptr){ node *temp=now->right; delete now; return temp; } now->left=deletemin(now->left); return now; } node* deletekey(node *now,int key) { if(now->key==key){ node* temp=findmin(now->right);// temp( ) temp->right=deletemin(now->right);// , , temp right。 temp->left=now->left;// left left return temp; }else if(now->keyright=deletekey(now->right,key); return now; }else{ now->left=deletekey(now->left,key); return now; } } }; int main() { bst a; a.insert(a.head,10); a.insert(a.head,15); a.insert(a.head,7); a.insert(a.head,4); a.insert(a.head,8); a.midout(a.head); cout<

좋은 웹페이지 즐겨찾기