第十二章:二叉查找树(1)

本文详细介绍了二叉查找树的基本操作,包括创建、搜索、查找最小值、最大值、后继节点及前驱节点等,并提供了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉查找树的基本操作

#include <iostream>
#include <stack>

using namespace std;

stack<TreeNode *> s;

typedef int Data;

struct TreeNode{
	Data data;
	TreeNode *parent;
	TreeNode *left;
	TreeNode *right;
};

//创建一颗查找二叉树
TreeNode *Create_Tree(int num){
	TreeNode *p=(TreeNode *)malloc(sizeof(TreeNode));
	TreeNode *root,*child,*parent;
	child=root=p;
	p->parent=p->left=p->right=NULL;
	cin>>root->data;
	int i=0;
	while (++i<num){
		TreeNode *p=(TreeNode *)malloc(sizeof(TreeNode));
		p->parent=p->left=p->right=NULL;
		cin>>p->data;
		child=root;
		while (child){
			parent=child;
			if (p->data>child->data){
				child=child->right;
			}else{
				child=child->left;
			}
		}
		if (p->data>parent->data){
			parent->right=p;
			p->parent=parent;
		}else{
			parent->left=p;
			p->parent=parent;
		}
	}
	return root;
}

TreeNode *Tree_Search(TreeNode *t,int key){
	while (t&&t->data!=key){
		if (t->data>key){
			t=t->left;
		}else{
			t=t->right;
		}
	}
	return t;
}

TreeNode *Minimum(TreeNode *t){
	while (t->left){
		t=t->left;
	}
	return t;
}

TreeNode *Maximum(TreeNode *t){
	while (t->right){
		t=t->right;
	}
	return t;
}

TreeNode *Tree_Successor(TreeNode *t){
	if (t->right){
		return Minimum(t->right);
	}else{
		while (t->parent&&t->parent->right==t){
			t=t->parent;
		}
		return t->parent;
	}
}

TreeNode *Tree_Predecessor(TreeNode *t){
	if (t->left){
		t=t->left;
		while (t->right){
			t=t->right;
		}
		return t;
	}else if (t->parent){
		return t->parent;	
	}
}

  

转载于:https://www.cnblogs.com/lsf90/p/3147147.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值