[C++] Binary search tree insertion, deletion, and search

#include<iostream>
using namespace std;
struct BinTreeNode
{
    
    
	int data;
	BinTreeNode* leftChild, * rightChild;
	BinTreeNode(int c, BinTreeNode* l = NULL,
		BinTreeNode* r = NULL) :data(c),
		leftChild(l), rightChild(r) {
    
    }

};
BinTreeNode* insert(BinTreeNode* root, int val) {
    
    
	if (root == NULL) {
    
    
		root = new BinTreeNode(val);
	}
	else {
    
    
		if (val < root->data) {
    
    
			root->leftChild = insert(root->leftChild, val);
		}
		else{
    
    
			root->rightChild = insert(root->rightChild, val);
		}
	}
	return root;
}
void preOrder(BinTreeNode* root) {
    
    
	if (root != NULL) {
    
    
		cout << root->data << " ";
		preOrder(root->leftChild);
		preOrder(root->rightChild);
	}
}
void inOrder(BinTreeNode* root) {
    
    
	if (root != NULL) {
    
    
		inOrder(root->leftChild);
		cout << root->data << " ";
		inOrder(root->rightChild);
	}
}
void postOrder(BinTreeNode* root) {
    
    
	if (root != NULL) {
    
    
		postOrder(root->leftChild);
		postOrder(root->rightChild);
		cout << root->data << " ";
	}
}
int main() {
    
    
	BinTreeNode* root = NULL;
	int num[] = {
    
     4,2,1,3,6,5,7 };
	for (int i = 0;i < 7;i++) {
    
    
		root = insert(root, num[i]);
	}
	cout << "先序遍历:";
	preOrder(root);
	cout << "\n";
	cout << "中序遍历:";
	inOrder(root);
	cout << "\n";
	cout << "后序遍历:";
	postOrder(root);
    return 0;
}




Insert picture description here
Insert picture description here

delete

Insert picture description here
When deleting a leaf node: delete it directly. Point the pointer of its parent node to NULL
Insert picture description here

When deleting only one child node: Point the pointer of its parent node to the child node of the deleted node.
Insert picture description here
When the deleted node has left and right subtrees: replace the deleted node with another node, the smallest element of the right subtree or the largest element of the left subtree.
Insert picture description here

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_48180029/article/details/114493056