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实现

    君子知命不惧,自当日日自新
  • 相关阅读:
    【LVS 】NAT方式实现过程
    【 LVS 】类型及算法
    [ 总结 ] RHEL6/Centos6 使用OpenLDAP集中管理用户帐号
    [ 手记 ] 关于tomcat开机启动设置问题
    [ 总结 ] nginx 负载均衡 及 缓存
    Mac
    Swift
    Swift
    Cocoapods
    Swift
  • 原文地址:https://www.cnblogs.com/xuxiaojin/p/9782213.html
Copyright © 2011-2022 走看看