C++二叉搜索树——插入

​ 通过结构体作为节点,结构体包含四个成员,分别是键值key,指向父节点的指针 *parent,指向左子节点的指针 *left,指向右子节点的指针 *right。

struct Node{
	int key;
	Node *left,*right,*parent;
}

​ 从根以起点寻找节点 x 的插入位置。 设当前节点为 x,如果 z 的键值小于 x 则将当前节点的左子节点作为下一个 x,反之则以右子节点作为下一个 x,如此不断向叶节点搜索。在此过程中,将 x 的前一个节点保存在 y 中,用作 z 的候选父节点。当x 到达 NIL 时结束搜索,此时的 y 节点就是 z 的父节点了。

#include <iostream>
#include <string>
using namespace std;

struct Node {
	int key;
	Node* left, * right, * parent;
};

Node* root, * NIL;
int H;

void InsertKey(int k) {
	Node* x = root;
	Node* y = NIL;
	Node* z = new Node;
	z->key = k;
	z->left = NIL;
	z->right = NIL;
	while (x != NIL) {
		y = x;
		if (z->key < x->key) {
			x = x->left;
		}
		else {
			x = x->right;
		}
	}
	z->parent = y;
	if (y == NIL) {
		root = z;
	}
	else {
		if (y->key > z->key) {
			y->left = z;
		}
		else {
			y->right = z;
		}
	}
}

void PreOrder(Node* u) {
	if (u == NIL)
		return;
	cout << u->key << " ";
	PreOrder(u->left);
	PreOrder(u->right);
}

void Inorder(Node* u) {
	if (u == NIL)
		return;
	Inorder(u->left);
	cout << u->key << " ";
	Inorder(u->right);
}

int main()
{
	int n, x;
	string com;
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> com;
		if (com == "insert") {
			cin >> x;
			InsertKey(x);
		}
		else if (com == "print") {
			printf("Inorder:");
			Inorder(root);
			printf("\n");
			printf("Preorder:");
			PreOrder(root);
			printf("\n");
		}
	}
	return 0;
}

/*
input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print
*/
/*
out put:
Inorder: 1 12 17 20 25 30 88
Preorder: 30 12 1 20 17 25 88
*/

考察:设树高为h,向二叉搜索树中插入元素的操作的复杂度为O(h)。若输入平衡,算法的复杂度就是O(logn)

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值