zoukankan      html  css  js  c++  java
  • 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的$().each,$.each的区别
    SpringMVC的几种返回方式
    MySQL创建数据库并赋予权限
    Java微信公众号开发
    Mybatis批量删除
    JavaMail邮件开发
    JSON 数组的遍历解析
    按小时统计的语句
    Linux下安装Redis3.2.4
  • 原文地址:https://www.cnblogs.com/xuxiaojin/p/9782213.html
Copyright © 2011-2022 走看看