1. 程式人生 > >C++二叉排序樹的基本操作

C++二叉排序樹的基本操作

#include<iostream>
#include<algorithm>

using namespace std;

typedef struct treenode {
	int data;
	treenode *lchild;
	treenode *rchild;
}*Node;

bool Insert(Node &root, int k) {  //插入資料
	if (root == NULL) {
		root = new treenode;
		root->data = k;
		root->lchild = NULL;
		root->rchild = NULL;
		return true;
	}
	else {
		if (k == root->data) {
			return false;
		}
		else {
			if (k < root->data) {
				return Insert(root->lchild, k);
			}
			else {
				return Insert(root->rchild, k);
			}
		}
	}
}

void Create(Node &root, int *A, int n) { //構造二叉樹
	int i = 0;
	while (i < n) {
		Insert(root, A[i]);  //插入元素
		i++;
	}

}

int Next(int *A,int k,int n) {  //尋找它的後繼
	for (int i = 0; i < n; i++) {
		if (A[i] == k && (i+1)<n ) {
			return A[i + 1];
		}
	}
}

Node Delete_one(Node t,int k,int n,int *A) {
	Node root = t;
	Node p = NULL;
	while (root != NULL && k != root->data) {
		p = root;
		if (k < root->data) {
			root = root->lchild;
		}
		else {
			root = root->rchild;
		}
	}

	if (root != NULL) {   //找到了這個節點
		if (root->lchild == NULL && root->rchild == NULL) { //葉子節點
			if (p->lchild == root) {  //置為空指標
				p->lchild = NULL;
			}

			if (p->rchild == root) {  //置為空指標
				p->rchild = NULL;
			}
			
				return root;
		}
		else {
			if (root->lchild != NULL && root->rchild == NULL) {
				if (p->lchild == root) {
					p->lchild = root->lchild;
				}
				
				if (p->rchild == root) {
					p->rchild = root->lchild;
				}

				return root;

			}
			else {
				if (root->lchild == NULL && root->rchild != NULL) {
					if (p->lchild == root) {
						p->lchild = root->rchild;
					}

					if (p->rchild == root) {
						p->rchild = root->rchild;
					}
					return root;
				}
				else {
					if (root->lchild != NULL && root->rchild != NULL) {
						Node temp = Delete_one(t, Next(A,n,k),n,A);  //獲得刪除的後繼節點
						if (p->lchild == root) {
							p->lchild = temp;
							temp->lchild = root->lchild;
							temp->rchild = root->rchild;
						}

						if (p->rchild == root) {
							p->rchild = temp;
							temp->lchild = root->lchild;
							temp->rchild = root->rchild;
						}
						return root;
					}
				}
			}
		}
	}
}

void Print(Node root) {
	if (root) {
		Print(root->lchild);
		cout << root->data << " ";
		Print(root->rchild);
	}
}

void Delete(Node &root) {
	if (root) {
		Delete(root->lchild);
		Delete(root->rchild);
		delete root;
	}
}


int main() {
	Node root = NULL;
	int A[9] = {8,3,2,7,5,4,1,0,6};
	Create(root, A, 9);
	Print(root);
	cout << endl;
	sort(A, A + 9);
	Delete_one(root, 4,9,A);
	Print(root);
	Delete(root);  //隨手刪除,好習慣
	system("pause");
	return 0;
}