• C++ 二叉搜索树


    二叉搜索树利用其特有的二叉树性质,使其搜索更方便

    源代码:

    struct node {
    	int val;
    	node *left, *right;
    };
    
    //the function of insert
    node *insert(node *n, int key) {
    	if (n == NULL) {
    		node *t = new node;
    		t->val = key;
    		t->left = t->right = NULL;
    		return t;
    	}
    	else {
    		if (key < n->val) n->left = insert(n->left, key);
    		else n->right = insert(n->right, key);
    		return n;
    	}
    }
    //the function of find_key
    bool find(node *n, int key) {
    	if (n == NULL) return false;
    	else if (key == n->val) return true;
    	else if (key > n->val) return find(n->right, key);
    	else return find(n->left, key);
    }
    
    //the function of remove
    node *remove(node *n, int key) {
    	if (n == NULL) return NULL;
    	else if (key < n->val) n->left = remove(n->left, key);
    	else if (key > n->val) n->right = remove(n->right, key);
    	else if (n->left == NULL) {
    		node *q = n->right;
    		delete n;
    		return q;
    	}
    	else if (n->left->right == NULL) {
    		node *q = n->left;
    		q->right = n->right;
    		delete n;
    		return q;
    	}
    	else {
    		node *q;
    		for (q = n->left; q->right->right != NULL; q = q->right);
    		node *r = q->right;
    		q->right = r->left;
    		r->left = n->left;
    		r->right = n->right;
    		delete n;
    		return r;
    	}
    	return n;
    }
    

      利用STL实现

    君子知命不惧,自当日日自新
  • 相关阅读:
    jQuery扩展函数设置所有对象只读
    Jquery一些实用函数
    原码,反码,补码
    数据库查询练习
    已知二叉树的先序遍历和中序遍历画出该二叉树
    linux 下 Google配置SwitchyOmega
    字母和数字转换
    c++产生验证码字符串
    C++产生随机数
    快速排序
  • 原文地址:https://www.cnblogs.com/xuxiaojin/p/9782213.html
Copyright © 2020-2023  润新知