SYSU_SECE_数据与结构_004

1.B树

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
 
class BTreeNode
{
    int *keys;  // An array of keys
    int t;      // Minimum degree (defines the range for number of keys)
    BTreeNode **C; // An array of child pointers
    int n;     // Current number of keys
    bool leaf; // Is true when node is leaf. Otherwise false
public:
    BTreeNode(int _t, bool _leaf);  
    void insertNonFull(int k);
    void splitChild(int i, BTreeNode *y);
    void traverseleft(BTreeNode *y);
	void traverseright(BTreeNode *y);

friend class BTree;
};
 
// A BTree
class BTree
{
    BTreeNode *root;
    int t;  
public:
    BTree(int _t)
    {  root = NULL;  t = _t; }

    void traverseleft()
    {  if (root != NULL) root->traverseleft(root); }
 
    void traverseright()
    {  if (root != NULL) root->traverseright(root); } 
    void insert(int k);
};
 

BTreeNode::BTreeNode(int t1, bool leaf1)
{
    t = t1;
    leaf = leaf1;
    keys = new int[2*t-1];
    C = new BTreeNode *[2*t];
    n = 0;
}
 

void BTreeNode::traverseleft(BTreeNode *y)
{
	if(y->leaf)
	{
		cout<<y->keys[0];
	}
	else{
		cout<<y->keys[0]<<" ";
		traverseleft(y->C[0]);
	}
}
void BTreeNode::traverseright(BTreeNode *y)
{
	if(y->leaf)
	{
		cout<<y->keys[(y->n)-1];
	}
	else{
		cout<<y->keys[(y->n)-1]<<" ";
		traverseright(y->C[(y->n)]);
	}
} 

 

void BTree::insert(int k)
{
   
    if (root == NULL)
    {
       
        root = new BTreeNode(t, true);
        root->keys[0] = k;  
        root->n = 1;  
    }
    else 
    {
       
        if (root->n == 2*t-1)
        {
          
            BTreeNode *s = new BTreeNode(t, false);
 
            
            s->C[0] = root;
 
            
            s->splitChild(0, root);
 

            int i = 0;
            if (s->keys[0] < k)
                i++;
            s->C[i]->insertNonFull(k);
 
       
            root = s;
        }
        else  
            root->insertNonFull(k);
    }
}
 

void BTreeNode::insertNonFull(int k)
{

    int i = n-1;
 
    if (leaf == true)
    {
        
        while (i >= 0 && keys[i] > k)
        {
            keys[i+1] = keys[i];
            i--;
        }
 
   
        keys[i+1] = k;
        n = n+1;
    }
    else 
    {
 
        while (i >= 0 && keys[i] > k)
            i--;

        if (C[i+1]->n == 2*t-1)
        {
            splitChild(i+1, C[i+1]);
            if (keys[i+1] < k)
                i++;
        }
        C[i+1]->insertNonFull(k);
    }
}

void BTreeNode::splitChild(int i, BTreeNode *y)
{

    BTreeNode *z = new BTreeNode(y->t, y->leaf);
    z->n = t - 1;
 

    for (int j = 0; j < t-1; j++)
        z->keys[j] = y->keys[j+t];
 
 
    if (y->leaf == false)
    {
        for (int j = 0; j < t; j++)
            z->C[j] = y->C[j+t];
    }
 
    y->n = t - 1;
 

    for (int j = n; j >= i+1; j--)
        C[j+1] = C[j];

    C[i+1] = z;
    for (int j = n-1; j >= i; j--)
        keys[j+1] = keys[j];
 

    keys[i] = y->keys[t-1];
 

    n = n + 1;
}

int main()
{
	int T,n;
	cin>>T>>n;
	
    BTree t(T);
    for(int i=1;i<=n;i++) t.insert(i);
    t.traverseleft();
    cout<<endl;
 	t.traverseright();

 
    return 0;
}

2.BST

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
typedef struct Node {
	Node *lchild;
	Node *rchild;
	char c;
}Node, *Tree;//静态内存分配数组
			 //int loc;
char str1[30];
char str2[30];
Node *createNode() {
	//    Tree[loc].lchild = Tree[loc].rchild=NULL;
	//    return &Tree[loc++];
	Tree node = (Tree)malloc(sizeof(Node));
	if (node) {
		node->lchild = node->rchild = nullptr;
		return node;
	}
	else {
		printf("无法分配节点");
		exit(0);
	}

}
//后序遍历算法
void postOrder(Node *T) {
	if (T->lchild != NULL) {
		postOrder(T->lchild);
	}
	if (T->rchild != NULL) {
		postOrder(T->rchild);
	}
	printf("%c", T->c);

}
//先序遍历
void preOrder(Tree T) {
	printf("%c", T->c);
	if (T->lchild != NULL) {
		preOrder(T->lchild);
	}
	if (T->rchild != NULL) {
		preOrder(T->rchild);
	}
}
//中序遍历
void midOrder(Tree T) {
	if (T->lchild != NULL) {
		midOrder(T->lchild);
	}
	printf("%c", T->c);
	if (T->rchild != NULL) {
		midOrder(T->rchild);
	}

}

Node * build(int s1, int e1, int s2, int e2) {
	//根据前序遍历序列str1和中序遍历序列str2构建树,并返回树的根节点,
	Node * ret = createNode();//构建根节点,
	ret->c = str1[s1];
	int rootIdx;
	for (int i = s2; i <= e2; i++) {
		if (str2[i] == str1[s1]) {
			rootIdx = i;//在中序遍历序列中找到根节点的下标;
			break;
		}
	}
	if (rootIdx != s2) {//说明左子树不为空
		ret->lchild = build(s1 + 1, s1 + (rootIdx - s2), s2, rootIdx - 1);
	}
	if (rootIdx != e2) {//说明右子树不为空
		ret->rchild = build(s1 + (rootIdx - s2) + 1, e1, rootIdx + 1, e2);

	}
	return ret;
}
//建立一颗二叉树,前序
Node *buildTree() {
	//输入字符建立二叉树,遇到#便设置这个节点为空
	Node *root = (Tree)malloc(sizeof(Node));
	char a;
	scanf_s("%c", &a);
	if (a == '#') {
		root = nullptr;
	}
	else {
		root->c = a;
		root->lchild = buildTree();
		root->rchild = buildTree();
	}
	return root;
}
//求树的高度
int high_Tree(Tree T) {
	if (T == nullptr) {
		return 0;
	}
	else {
		int lh = high_Tree(T->lchild);
		int rh = high_Tree(T->rchild);
		return lh>rh ? lh + 1 : rh + 1;
	}

}
int main() {
	while (scanf_s("%s", str1) != EOF) {
		scanf_s("%s", str2);
		int L1 = strlen(str1);
		int L2 = strlen(str2);
		Node * T = build(0, L1 - 1, 0, L2 - 1);
		postOrder(T);
		printf("%d\n", high_Tree(T));
		printf("\n");
	}
	return 0;
}

3.二叉树的三种遍历输出

//二叉树的节点结构
typedef struct _TreeNode
{
	int _data;
	struct _TreeNode * _left;
	struct _TreeNode * _right;
}TreeNode;
//使用递归进行先序遍历
void preOrderTraverse(TreeNode *root){
	// 如果根节点存在
	if (root)
	{
		cout << root->_data << " ";
		preOrderTraverse(root->_left);
		preOrderTraverse(root->_right);
	}
}
//使用递归进行中序遍历
void midOrderTraverse(TreeNode *root){
	// 如果根节点存在
	if (root)
	{
		midOrderTraverse(root->_left);
		cout << root->_data << " ";
		midOrderTraverse(root->_right);
	}
}
//使用递归进行后序遍历
void postOrderTraverse(TreeNode *root){
	// 如果根节点存在
	if (root)
	{
		postOrderTraverse(root->_left);
		postOrderTraverse(root->_right);
		cout << root->_data << " ";
	}
}

//完整代码
#include <stdio.h>
#include <iostream>
using namespace std;
 
typedef struct _TreeNode
{
	int _data;
	struct _TreeNode * _left;
	struct _TreeNode * _right;
}TreeNode;
 
 
// 前序遍历
void preOrderTraverse(TreeNode *root){
	// 如果根节点存在
	if (root)
	{
		cout << root->_data << " ";
		preOrderTraverse(root->_left);
		preOrderTraverse(root->_right);
	}
}
 
// 中序遍历
void midOrderTraverse(TreeNode *root){
	// 如果根节点存在
	if (root)
	{
		midOrderTraverse(root->_left);
		cout << root->_data << " ";
		midOrderTraverse(root->_right);
	}
}
 
// 后序遍历
void postOrderTraverse(TreeNode *root){
	// 如果根节点存在
	if (root)
	{
		postOrderTraverse(root->_left);
		postOrderTraverse(root->_right);
		cout << root->_data << " ";
	}
}
 
// 创建一棵树
int main(int argc, char const *argv[])
{
	TreeNode a, b, c, d, e, f;
	// 创建一个指向根节点的指针
	TreeNode* root  = &a;
	a._data = 1;
	b._data = 2;
	c._data = 3;
	d._data	= 4;
	e._data = 5;
	f._data = 6;
	a._left = &b;
	a._right = &c;
	b._left = &d;
	b._right = &e;
	c._left = NULL;
	c._right = &f;
	d._left = d._right = NULL;
	e._left = e._right = NULL;
	f._left = f._right = NULL;
 
	preOrderTraverse(root);
	cout << endl;
	midOrderTraverse(root);
	cout << endl;
	postOrderTraverse(root);
	cout << endl;
 
	return 0;
}

4.根据先序和中序遍历确定二叉树的后序遍历

#include<iostream>//根据先序和中序遍历确定二叉树的后序遍历
#include<string>   //输入的元素以空格进行分割
#include<cstring>   //输出二叉树后序遍历结果,记得带空格
using namespace std;
const int M = 1024;
char pr[M];
char in[M];

struct node
{
	char data;
	node *l;
	node *r;
};
void create(node * &t, int preL, int preR, int inL, int inR) {
	if (preL > preR)
	{
		t = NULL;
		return;
	}
	t = new node();
	t->data = pr[preL];
	int index;
	for (index = inL; index <= inR; index++) {
		if (in[index] == pr[preL])break;
	}
	int numLeft = index - inL;
	create(t->l, preL + 1, preL + numLeft, inL, index - 1);
	create(t->r, preL + numLeft + 1, preR, index + 1, inR);
}

void post_display(const node *t)
{
	if (t == NULL)
		return;
	post_display(t->l);
	post_display(t->r);
	printf("%c ", t->data);
}

int main()
{

	memset(pr, '\0', sizeof(pr));
	memset(in, '\0', sizeof(in));

	string a, b;
	getline(cin, a);
	int k = 0;
	for (int i = 0; i < a.size(); i++) {
		if (a[i] != ' ') {
			pr[k] = a[i];
			k++;//strlen(pr)
		}
	}
	int y = 0;
	getline(cin, b);
	for (int j = 0; j < b.size(); j++) {
		if (b[j] != ' ') {
			in[y] = b[j];
			y++;
		}
	}
	//while (cin >> pr&&cin >> in)
		node *tree = NULL;
		//if (strlen(pr) == strlen(in))
		//{
			//create(tree, 0, strlen(pr) - 1, 0, strlen(pr) - 1);
			//cout << "build tree ok" << endl;
		//}
		//cout<<tree<<endl<<tree->l<<endl<<tree->r<<endl;
		create(tree, 0, k - 1, 0, y - 1);

		post_display(tree);
		cout << endl;
		memset(pr, '\0', sizeof(pr));
		memset(in, '\0', sizeof(in));
		system("pause");
}
/*
由于输入的字符串中间含有空格,所以利用string格式的字符串进行读取
然后利用循环判断,不是空格的才赋值给pr和in数组
string a;
getline(cin, a);
cout << a << endl;
cout << a.size() << endl;
*/

5.构建二叉树并实现访问操作

class Node(object):
    def __init__(self, lchild=None, rchild=None, elem=0):
        self._elem, self._lchild, self._rchild = elem, lchild, rchild

    @property
    def elem(self):
        if self._elem is '#':
            return None
        return self._elem

    @property
    def lchid(self):
        return self._lchild

    @property
    def rchild(self):
        return self._rchild

    @elem.setter
    def elem(self, elem):
        self._elem = elem

    @lchid.setter
    def lchild(self, lchild):
        self._lchild = lchild

    @rchild.setter
    def rchild(self, rchild):
        self._rchild = rchild


class BinTree(object):
    def __init__(self, elem=None):
        if elem is not None:
            self.root = Node(None, None, elem)
        else:
            self.root = None

    def append(self, elem):
        if self.root is None:
            self.root = Node(None, None, elem)
        else:
            queue = [self.root]
            while len(queue) > 0:
                cur = queue.pop(0)
                if cur.lchild is None:
                    cur.lchild = Node(None, None, elem)
                    return
                elif cur.rchild is None:
                    cur.rchild = Node(None, None, elem)
                    return
                else:
                    queue.append(cur.lchild)
                    queue.append(cur.rchild)

    def layer_order(self):
        if self.root is None:
            print('None')
        else:
            queue = [self.root]
            while queue:
                node = queue.pop(0)
                print(node.elem)
                if node.lchild is not None:
                    queue.append(node.lchild)
                if node.rchild is not None:
                    queue.append(node.rchild)


if __name__ == '__main__':

    #####################################

    #   接收处理第一行数据并构造树的代码区域   #
    MyTree = BinTree()
    temp_list = list(input().split(" "))
    if temp_list != ['']:
        for i in range(len(temp_list)):
            MyTree.append(temp_list[i])

    #####################################

   # MyTree.layer_order()

    N = int(input())
    if N!=1:
        for i in range(N):
            print(eval(input()))
    else:
        print("None")
#注意tap与四个空格的区别    Indent expected代码缩进问题

6.构建红黑树-RBTREE

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

#define RED 0
#define BLACK 1

//定义红黑树结点 
typedef struct RBTreeNode
{
	char color;//颜色 
	int key;//值 
	struct RBTreeNode *lchild;//左孩子 
	struct RBTreeNode *rchild;//右孩子 
	struct RBTreeNode *parent;//父结点 
}Node, *RBTree;

//定义红黑树根结点
typedef struct rb_root
{
	Node *node;
} RBRoot;

//创建红黑树,返回红黑树的根
RBRoot* creat_rbtree()
{
	RBRoot *root = (RBRoot*)malloc(sizeof(RBRoot));//定义根结点,并分配空间 
	root->node = NULL;//初始化 
	return root;
}

//新建一个结点
Node*  creat_rbtree_node(int key, Node *parent, Node *lchild, Node *rchild)
{
	Node* p;
	p = (Node*)malloc(sizeof(Node));
	p->key = key;
	p->lchild = lchild;
	p->rchild = rchild;
	p->color = BLACK;

	return p;
}

//左旋 
void rbtree_left_rotate(RBRoot *root, Node *x)
{
	Node *y = x->rchild;//设置x的右结点等于y
						//首先,先找到y的左孩子,它最终被x收养为右孩子 
	x->rchild = y->lchild;
	if (y->lchild != NULL)
		y->lchild->parent = x;

	y->parent = x->parent;
	//x->rchild=y->lchild;
	//y->lchild->parent=x;

	//y缺了左孩子,x成为y的左孩子
	if (x->parent == NULL)//当x为根结点的时候
	{
		root->node = y;//将y设为根结点 
	}
	else//当x不是根节点的时候 
	{
		//y->parent=x->parent;//y接替x做别人的儿子 
		if (x->parent->lchild == x) //要确定y是做的左孩子还是右孩子 
		{
			x->parent->lchild = y;
		}
		else
		{
			x->parent->rchild = y;
		}
	}
	y->lchild = x;//x就位 
	x->parent = y;
	//printf("(对关键字%d进行左旋)",x->key);
}

//右旋 
void rbtree_right_rotate(RBRoot *root, Node *y)
{
	Node *x = y->lchild;

	y->lchild = x->rchild;
	//找到x的右孩子,它最终被y收养为左孩子
	if (x->rchild != NULL)
	{
		x->rchild->parent = y;
	}
	x->parent = y->parent;
	//此时x的右孩子是空的,y来当x的右孩子
	if (y->parent == NULL)//如果y为根结点
	{
		root->node = x;//将x设为根节点 
	}
	else//当y不是根节点的时候 
	{
		//y->parent=x->parent;//x接替y做别人的儿子 
		if (y->parent->rchild == y) //要确定x是做的左孩子还是右孩子 
		{
			y->parent->rchild = x;
		}
		else
		{
			y->parent->lchild = x;
		}
	}
	x->rchild = y;//y就位 
	y->parent = x;
	//printf("(对关键字%d进行右旋)",y->key);
}

//插入修正 
void rbtree_insert_fixup(RBRoot *root, Node *node)
{
	Node *parent, *gparent;
	// 若父节点存在,并且父节点的颜色是红色
	while ((parent = node->parent) && (parent->color == RED))
	{
		gparent = parent->parent;

		//若“父节点”是“祖父节点的左孩子”
		if (parent == gparent->lchild)
		{
			// Case 1条件:叔叔节点是红色
			{
				Node *uncle = gparent->rchild;
				if (uncle && uncle->color == RED)
				{//父、叔变黑,爷变红,对爷进行判断 
					uncle->color = BLACK;
					parent->color = BLACK;
					gparent->color = RED;
					node = gparent;
					continue;
				}
			}

			// Case 2条件:叔叔是黑色,且当前节点是右孩子
			if (parent->rchild == node)
			{
				Node *tmp;
				rbtree_left_rotate(root, parent);//父左旋 
				tmp = parent;
				parent = node;
				node = tmp;
			}

			// Case 3条件:叔叔是黑色,且当前节点是左孩子。
			parent->color = BLACK;
			gparent->color = RED;
			rbtree_right_rotate(root, gparent);
		}
		else//若“z的父节点”是“z的祖父节点的右孩子”
		{
			// Case 1条件:叔叔节点是红色
			{
				Node *uncle = gparent->lchild;
				if (uncle && (uncle->color == RED))
				{
					uncle->color = BLACK;
					parent->color = BLACK;
					gparent->color = RED;
					node = gparent;
					continue;
				}
			}

			// Case 2条件:叔叔是黑色,且当前节点是左孩子
			if (parent->lchild == node)
			{
				Node *tmp;
				rbtree_right_rotate(root, parent);
				tmp = parent;
				parent = node;
				node = tmp;
			}

			// Case 3条件:叔叔是黑色,且当前节点是右孩子。
			parent->color = BLACK;
			gparent->color = RED;
			rbtree_left_rotate(root, gparent);
		}
	}

	// 将根节点设为黑色
	root->node->color = BLACK;
	//printf("对关键字%d进行插入修正",node->key);
}

//插入
void rbtree_insert(RBRoot *root, Node *node)
{
	Node *y = NULL;
	Node *x = root->node;

	while (x != NULL)//x为叶子结点跳出循环 
	{
		y = x;
		if (x->key>node->key)
		{
			x = x->lchild;
		}
		else
		{
			x = x->rchild;
		}
	}
	node->parent = y;

	if (y != NULL)
	{
		if (node->key<y->key)
		{
			y->lchild = node;
		}
		else
		{
			y->rchild = node;
		}
	}
	else
	{
		root->node = node;//若y为NULL,说明树为空,则将node设为根节点 
	}

	node->color = RED;//将颜色设为红色

					  //插入修正 
	rbtree_insert_fixup(root, node);
}

int insert_rbtree(RBRoot *root, int key)
{
	Node *node;//新建一个结点
	node = creat_rbtree_node(key, NULL, NULL, NULL);
	if (node == NULL) return -1;
	else rbtree_insert(root, node);
	return 0;
}


/*
* 中序遍历"红黑树"//前序遍历红黑树
*/
void inorder(RBTree tree)
{
	if (tree != NULL)
	{
		printf("%d ", tree->key);
		inorder(tree->lchild);	
		inorder(tree->rchild);
	}
}

void inorder_rbtree(RBRoot *root)
{
	if (root)
		inorder(root->node);
}
void Judge_color(RBTree tree) {
	if (tree != NULL) {
		if (tree->color == 0) {
			printf("0 ");
		}
		else
			printf("1 ");
		Judge_color(tree->lchild);//前序
		Judge_color(tree->rchild);//前序输出结点颜色
	}
}
void Judge(RBRoot *root) {
	if (root)
		Judge_color(root->node);
}
int main()
{
	int key[50], k = 0, n;
	while (cin >> n) {
		key[k] = n;
		k++;
		if (getchar() == '\n')break;
	}
	//int a[8] = { 11, 5 ,9 ,10, 3, 4 ,1 ,20 };
	//int i;//计数器
	//int key;
	//int n = sizeof(a) / sizeof(int);
	
	//printf("**********原始数据**********\n");
	//for (i = 0; i<n; i++)
	//{
	//	printf("%d  ", a[i]);
	//}
	//printf("\n");

	//下面开始创建红黑树 
	RBRoot *root = NULL;//首先创建红黑树的根 
	root = creat_rbtree();

	for (int i = 0; i<k; i++)
	{
		//printf("== 添加节点: %d\n", a[i]);
		insert_rbtree(root, key[i]);
		//printf("== 中序遍历: ");
		
	}
	inorder_rbtree(root);
	printf("\n");
	Judge(root);
	//printf("\n");
	//printf("==向红黑树中插入一个值: ");
	//scanf_s("%d", &key);
	//insert_rbtree(root, key);
	//printf("\n== 成功插入后的中序遍历: ");
	//inorder_rbtree(root);
	//printf("\n");
	system("pause");
}

7.构造AVL树

#include<iostream>
#include<algorithm>
#include<time.h>
using namespace std;

typedef int T;

typedef struct AVLtree
{
	T value;
	T Height;
	AVLtree* left;
	AVLtree* right;
}AVLtree;

static T max(T a, T b)
{
	if (a>b)
	{
		return a;
	}
	else
	{
		return b;
	}
}
static T Get_H(AVLtree* tree)	//获取结点的平衡度(之后与2作对比来确定旋转方式) 
{
	if (NULL == tree)
		return -1;

	return tree->Height;
}

//旋转的实现 
AVLtree* LL_rotation(AVLtree* tree)
{
	AVLtree* temp;

	temp = tree->left;
	tree->left = temp->right;
	temp->right = tree;

	tree->Height = max(Get_H(tree->left), Get_H(tree->right)) + 1;
	temp->Height = max(Get_H(temp->left), Get_H(temp->left)) + 1;

	return temp;
}
AVLtree* RR_rotation(AVLtree* tree)
{
	AVLtree* temp;

	temp = tree->right;
	tree->right = temp->left;
	temp->left = tree;

	tree->Height = max(Get_H(tree->left), Get_H(tree->right)) + 1;
	temp->Height = max(Get_H(temp->right), Get_H(temp->left)) + 1;

	return temp;
}
AVLtree* LR_rotation(AVLtree* tree)		//递归调用,先RR再LL 
{
	tree->left = RR_rotation(tree->left);
	return LL_rotation(tree);
}
AVLtree* RL_rotation(AVLtree* tree)		//递归调用,先LL再RR 

{
	tree->right = LL_rotation(tree->right);
	return RR_rotation(tree);
}

//插入新结点的实现

AVLtree* AVLinsert(T x, AVLtree* tree)
{
	if (tree == NULL)
	{
		tree = (AVLtree*)malloc(sizeof(AVLtree));		//申请内存空间,malloc需要的头文件是algorithm.h 
		tree->value = x;
		tree->Height = 0;
		tree->left = tree->right = NULL;
	}

	else if (tree->value>x)		//由二叉搜索树性质知此时插入左子树
	{
		tree->left = AVLinsert(x, tree->left);

		if (Get_H(tree->left) - Get_H(tree->right) == 2)
		{
			if ((tree->left)->value>x)		//还是插入左边,则进行LL旋转
			{
				tree = LL_rotation(tree);
			}
			else		//否则进行LR操作
			{
				tree = LR_rotation(tree);
			}
		}
	}

	else if (tree->value<x) 		//由二叉搜索树性质知此时插入右子树
	{
		tree->right = AVLinsert(x, tree->right);

		if (Get_H(tree->right) - Get_H(tree->left) == 2)
		{
			if ((tree->right)->value<x)		//还是插入右边,则进行RR旋转
			{
				tree = RR_rotation(tree);
			}
			else		//否则进行RL操作
			{
				tree = RL_rotation(tree);
			}
		}
	}

	tree->Height = max(Get_H(tree->left), Get_H(tree->right)) + 1;
	return tree;
}

void AVLprint(AVLtree* tree)			//为求有序,按中序遍历输出AVL树 
{
	cout << tree->value << endl;
	if (tree->left != NULL)
	{
		AVLprint(tree->left);
	}
	//cout << tree->value <<endl;
	if (tree->right != NULL)
	{
		AVLprint(tree->right);
	}
}

void AVLdelete(AVLtree** t)		//释放内存空间 
{
	if (NULL == t || NULL == *t)
		return;

	AVLdelete(&((*t)->left));
	AVLdelete(&((*t)->right));
	free(*t);
	*t = NULL;
}

int main()  		//can use 随机数组验证AVL树的实现 
{
	T i=0, temp;
	AVLtree* tree = NULL;
	srand(time(NULL));

	int m, key[100];
	while (cin >> m) {//读取未知个数的整型数组
		key[i] = m;
		i++;
		if (getchar() == '\n')break;
	}

	for (int j = 0; j < i; j++)
	{
		//temp = rand();
		//cout << temp << endl;
		//tree = AVLinsert(temp, tree);
		temp = key[j];
		//cout << key[j];
		tree = AVLinsert(temp, tree);
	}
	//cout << endl;
	AVLprint(tree);
	AVLdelete(&tree);
	system("pause");
}

8.判断是否是AVL树

#include<iostream>
#include<algorithm>
#include<time.h>
#include<string>
#include<vector>
#include<sstream>
using namespace std;

typedef int T;
//通过比较输入的层序序列与构造成AVL树后正确的层序序列相比较,
//若完全相同,说明输入的是AVL树,如果不同,则不是AVL树
typedef struct AVLtree
{
	T value;
	T Height;
	AVLtree* left;
	AVLtree* right;
}AVLtree;

typedef AVLtree * pAVLtree;

static T max(T a, T b)
{
	if (a>b)
	{
		return a;
	}
	else
	{
		return b;
	}
}
static T Get_H(AVLtree* tree)	//获取结点的平衡度(之后与2作对比来确定旋转方式) 
{
	if (NULL == tree)
		return -1;

	return tree->Height;
}

//旋转的实现 
AVLtree* LL_rotation(AVLtree* tree)
{
	AVLtree* temp;

	temp = tree->left;
	tree->left = temp->right;
	temp->right = tree;

	tree->Height = max(Get_H(tree->left), Get_H(tree->right)) + 1;
	temp->Height = max(Get_H(temp->left), Get_H(temp->left)) + 1;

	return temp;
}
AVLtree* RR_rotation(AVLtree* tree)
{
	AVLtree* temp;

	temp = tree->right;
	tree->right = temp->left;
	temp->left = tree;

	tree->Height = max(Get_H(tree->left), Get_H(tree->right)) + 1;
	temp->Height = max(Get_H(temp->right), Get_H(temp->left)) + 1;

	return temp;
}
AVLtree* LR_rotation(AVLtree* tree)		//递归调用,先RR再LL 
{
	tree->left = RR_rotation(tree->left);
	return LL_rotation(tree);
}
AVLtree* RL_rotation(AVLtree* tree)		//递归调用,先LL再RR 

{
	tree->right = LL_rotation(tree->right);
	return RR_rotation(tree);
}

//插入新结点的实现

AVLtree* AVLinsert(T x, AVLtree* tree)
{
	if (tree == NULL)
	{
		tree = (AVLtree*)malloc(sizeof(AVLtree));		//申请内存空间,malloc需要的头文件是algorithm.h 
		tree->value = x;
		tree->Height = 0;
		tree->left = tree->right = NULL;
	}

	else if (tree->value>x)		//由二叉搜索树性质知此时插入左子树
	{
		tree->left = AVLinsert(x, tree->left);

		if (Get_H(tree->left) - Get_H(tree->right) == 2)
		{
			if ((tree->left)->value>x)		//还是插入左边,则进行LL旋转
			{
				tree = LL_rotation(tree);
			}
			else		//否则进行LR操作
			{
				tree = LR_rotation(tree);
			}
		}
	}

	else if (tree->value<x) 		//由二叉搜索树性质知此时插入右子树
	{
		tree->right = AVLinsert(x, tree->right);

		if (Get_H(tree->right) - Get_H(tree->left) == 2)
		{
			if ((tree->right)->value<x)		//还是插入右边,则进行RR旋转
			{
				tree = RR_rotation(tree);
			}
			else		//否则进行RL操作
			{
				tree = RL_rotation(tree);
			}
		}
	}

	tree->Height = max(Get_H(tree->left), Get_H(tree->right)) + 1;
	return tree;
}
/*
void AVLprint(AVLtree* tree)			//为求有序,按中序遍历输出AVL树 
{
	cout << tree->value << endl;
	if (tree->left != NULL)
	{
		AVLprint(tree->left);
	}
	//cout << tree->value <<endl;
	if (tree->right != NULL)
	{
		AVLprint(tree->right);
	}
}*/
void AVLdelete(AVLtree** t)		//释放内存空间 
{
	if (NULL == t || NULL == *t)
		return;

	AVLdelete(&((*t)->left));
	AVLdelete(&((*t)->right));
	free(*t);
	*t = NULL;
}

int main()  		//can use 随机数组验证AVL树的实现 
{
	string s, s1;//接收字符串
	int i = 1;
	vector<string> vec;//储存层序遍历结果
	vec.push_back("#");
	getline(cin, s);//获得整行输入
	stringstream ss(s);
	while (getline(ss, s1, ' ')) {
		i++;
		vec.push_back(s1);
	}
	//cout << i << endl;
	//for (int j = 1; j < i; j++)
		//cout << vec[j] << endl;

	T temp;
	int chushi[100],chushi_c=0;
	AVLtree* tree = NULL;
	srand(time(NULL));
	for (int k = 1; k < i; k++) {
		if (vec[k] == "#") {}
		else {
			temp = stoi(vec[k]);//string转化为int型
			chushi[chushi_c] = temp;//有值的储存在chushi数组中(去掉了所有的#)
			//cout  << chushi[chushi_c] << endl;
			chushi_c++;
			tree = AVLinsert(temp, tree);
		}
	}
	int floor[100],f_c=0;
	pAVLtree temp2[100];
	int in = 0, out = 0;
	temp2[in++] = tree;
	while (in > out) {//层序遍历AVL树
		if (temp2[out]) {
			floor[f_c] = temp2[out]->value;
			temp2[in++] = temp2[out]->left;
			temp2[in++] = temp2[out]->right;
			f_c++;
			//cout << floor[f_c] << endl;
		}
		out++;
	}
	int judge = 1;
	for (int p = 0; p < chushi_c; p++) {
		if (chushi[p] == floor[p]) { }//比较两个层序遍历序列是否相等
		else {
			judge = 0; break;
		}
		//cout << judge << endl;
	}
	if (judge == 0)
		cout << "False";
	else
		cout << "True";
	system("pause");
}
	/*


	int all[100], count = 0;



	T i=0, temp;
	AVLtree* tree = NULL;
	srand(time(NULL));

	int m, key[100];
	while (cin >> m) {//读取未知个数的整型数组
		key[i] = m;
		i++;
		if (getchar() == '\n')break;
	}

	for (int j = 0; j < i; j++)
	{
		//temp = rand();
		//cout << temp << endl;
		//tree = AVLinsert(temp, tree);
		temp = key[j];
		//cout << key[j];
		tree = AVLinsert(temp, tree);
	}
	//cout << endl;
	AVLprint(tree);
	AVLdelete(&tree);
	system("pause");
}*/

9.蒙特卡洛算法计算圆周率

#include <iostream>
#include <cstdlib>//蒙特卡罗算法计算圆周率
#include <ctime>
using namespace std;

int main()
{
	srand((int)time(0));  // 产生随机种子  把0换成NULL也行
	double num;
	double count = 0;
	cin >> num;
	for (int i = 0; i < num; i++)
	{
		//cout << rand() % 10 << " ";
		//cout << rand() % 100 << endl;
		int x = rand() % 100;
		int y = rand() % 100;
		if ((x - 50)*(x - 50) + (y - 50)*(y - 50) <= 2500) {
			count++;
		}
	}
	cout << 4 * count / num;
	//system("pause");
}


#include <stdio.h>
#include <stdlib.h>
#define RENDER_MAX 100000
//生成L-R 范围内的随机数
double Rand(double L, double R){

        double ret;

        ret = L + (R-L)*rand()*1.0/RAND_MAX;

        return ret;

}
int main(){

        srand(time(NULL));

        int i;

        int count = 0;

        for(i=0;i<RENDER_MAX; i++){

                double x,y;

                x = Rand(-1,1);

                y = Rand(-1,1);

                if(x*x + y*y <= 1){   //求到中心的长度,即是否在圆圈内

                        count ++;

                }

        }
        printf("%f\n",4.0*count/RENDER_MAX );  //比例*4

}

10.戈尼斯堡七桥问题

#include<iostream>
//哥尼斯堡七桥问题
using namespace std;
int main() {
	int n, m;
	//若欧拉回路存在输出1,否则输出0
	cin >> n >> m;
	int num[1000] = { 0 };
	int count = 1;//important输入也算一个了
	int judge = 0;
	for (int i = 0; i < 2 * m; i++) {
		cin >> num[i];
	}
	for (int j = 0; j < 2 * m-1; j++) {
		if (num[j] != 0) {
			for (int k = j + 1; k < 2 * m; k++) {
				if (num[j] == num[k]) {
					count++;
					//cout << num[k] << endl;
					num[k] = 0;
				}
			}
			//cout << count << endl;
			if (count % 2 == 1) {
				judge++;
			}
		}
		count = 1;//important  
	}
	//cout << judge << endl;
	if (judge == 0) {
		cout << 1;
	}
  //寄点数为0或2时才能走通
	else
		cout << 0;
	//system("pause");
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SmallC1oud

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值