递归查询的使用

递归优点:

1. 简洁

2.在树的前序,中序,后序遍历算法中,递归的实现明显要比循环简单得多。

递归缺点:

1.递归由于是函数调用自身,而函数调用是有时间和空间的消耗的:每一次函数调用,都需要在内存栈中分配空间以保存参数、返回地址以及临时变量,而往栈中压入数据和弹出数据都需要时间。->效率

2.递归中很多计算都是重复的,由于其本质是把一个问题分解成两个或者多个小问题,多个小问题存在相互重叠的部分,则存在重复计算,如fibonacci斐波那契数列的递归实现。->效率

3.调用栈可能会溢出,其实每一次函数调用会在内存栈中分配空间,而每个进程的栈的容量是有限的,当调用的层次太多时,就会超出栈的容量,从而导致栈溢出。->性能

递归与非递归的对比

用递归首先要找到规律,然后要有一个出口

	/**
	 * 非递归方式求阶乘
	 * @param n
	 * @return
	 */
	static long notDigui(int n){
		long result=1;
		for(int i=1;i<=n;i++){
			result=result*i;
		}
		return result;
	}
	
	/**
	 * 递归方式
	 * @param n
	 * @return
	 */
	static long digui(int n){
		if(n==1){
			return 1;
		}
		return n*digui(n-1);
	}
	
	public static void main(String[] args) {
		System.out.println(Demo03.notDigui(5));  // 1*2*3*4*5
		System.out.println(Demo03.digui(5));
	}

非递归查询

	@Override
	public List<Map<String, Object>> getHistorymonitory() {
		// TODO Auto-generated method stub
		List<Map<String, Object>> treeNodes = new ArrayList<Map<String, Object>>();
		Map<String, Object> rtnNode = new HashMap<String, Object>();
		List<Map<String, Object>> rtnNodes = new ArrayList<Map<String, Object>>();
		Area area = new Area();
		area.setLevel(3);
		List<Area> areaList = mapper.select(area);
	    for(Area areas : areaList) {
	    	List<Map<String, Object>> childrens = new ArrayList<Map<String, Object>>();	
	    	Map<String, Object> treeNode = new HashMap<String, Object>();
	    	treeNode.put("id", areas.getAreaId());
	    	treeNode.put("text", areas.getAreaName());
	    	treeNode.put("flag", "1");
	    	/*查询街道对应的用户*/
	    	List<PublicServicesUser> idByStreet = publicServicesUserService.getIdByStreet(areas.getAreaId());
	    	
	    	/*PublicServicesUser publicServicesUser = new PublicServicesUser();
	    	publicServicesUser.setStreetTown(areas.getAreaId().toString());
	    	List<PublicServicesUser> select = publicServicesUserMapper.select(publicServicesUser);*/
	    	
	    	for(PublicServicesUser users:idByStreet) {
	    		Map<String, Object> children = new HashMap<String, Object>();
	    		children.put("id", users.getId());
	    		children.put("text", users.getUserName());
	    		children.put("flag", "0");
	    		childrens.add(children);
	    	}
	    	if(childrens.size()>0) {
	    		treeNode.put("children", childrens);
	    	}else {
	    		treeNode.put("children", null);
	    	}
	    	treeNodes.add(treeNode);	
	    }
	    rtnNode.put("id", -1);
	    rtnNode.put("text", "街道");
	    rtnNode.put("flag", "1");
	    rtnNode.put("children", treeNodes);
	    rtnNodes.add(rtnNode);
		return rtnNodes;
	}

递归查询

	@GetMapping("/getDicByCodes/{dictCodes}")
	public AssembleJSON getDicByCodes(@PathVariable String dictCodes) {
		SessionData sessionData = getCurrUserData();
		int userId = sessionData.getUserId();
		String orgManageDataCode = sessionData.getOrgManageDataCode();
		String orgDataCode = sessionData.getOrgDataCode();
		Integer orgLevel = sessionData.getOrgLevel();
		return AssembleJSON.SUCCESS(service.getDicByCodes(dictCodes,userId,orgManageDataCode,orgDataCode,orgLevel));
	}

@Override
	public Hashtable<String, List<DicItem>> getDicByCodes(String dictCodes,Integer userId, String orgManageDataCode,String orgDataCode, Integer orgLevel){
		Hashtable<String,List<DicItem>> hashtable = new Hashtable<>();
		String[] codes = dictCodes.split(",");
		List<DicItem> dicItems = new ArrayList<>();
		for(String code : codes){
			dicItems = getDicByCode(code,userId,orgManageDataCode,orgDataCode,orgLevel);
			if(dicItems != null){
				hashtable.put(code, dicItems);
			}
		}
		return hashtable;
	}
	
	@Override
	public List<DicItem> getDicByCode(String dictCode,Integer userId, String orgManageDataCode,String orgDataCode, Integer orgLevel) {
		Dictionary dictionary1 = new Dictionary();
		dictionary1.setDictCode(dictCode);
		Dictionary dictionary = mapper.selectOne(dictionary1);
		if(dictionary == null){
			return null;
		}
		List<DicItem> listDic = new ArrayList<>();
		if(dictionary != null){		
			if(dictionary.getDictType() == 1){
				List<DictionaryItem> list = dictionaryItemMapper.selectDictionaryItemAll(dictCode);
				getDicList(list,listDic);
			}else{
				String source1 = dictionary.gettSource();
				if(source1 == null || "".equals(source1)){
					return null;
				}
				String source = "";
				String source2 = "";
				String source3 = "";
				String source4 = "";
				source2 = source1.replace("{@sys_orgDataCode@}", orgDataCode);
				source3 = source2.replace("{@sys_userId@}", String.valueOf(userId));			
				source4 = source3.replace("{@sys_orgManageDataCode@}", orgManageDataCode);
				source = source4.replace("{@sys_orgLevel@}",String.valueOf(orgLevel));
				String code = dictionary.getfCode();
				String name = dictionary.getfName();
				String sort = dictionary.getfSort();
				String pField = dictionary.getpField();
			    List<DictionaryItem> list = new ArrayList<>();
			    if(sort == null || "".equals(sort)){
			    	if(pField == null || "".equals(pField)){
			    		list = mapper.selectDictionary(code, name, source,"'"+sort+"'");
			    	}else{
			    		list = mapper.selectDictionaryParent(code, name, source,"'"+sort+"'",pField);
			    	}	   
			    }else{
			    	if(pField == null || "".equals(pField)){
			    		list = mapper.selectDictionary(code, name, source,sort);
			    	}else{
			    		list = mapper.selectDictionaryParent(code, name, source,sort,pField);
			    	}	  
			    }			   
			getDicList(list,listDic);				
			}
		}
		return listDic;
	}
	

 

public void getDicList(List<DictionaryItem> list,List<DicItem> listDic){
		if(list.size() == 1){
			for(DictionaryItem dItem : list){				
					DicItem dic = new DicItem();
					dic.setId(dItem.getItemCode());
					dic.setText(dItem.getItemName());
					listDic.add(dic);
			}
		}else{
			boolean flag = true;
			for(DictionaryItem dItem : list){	
				if(dItem.getParentCode() == null || "".equals(dItem.getParentCode())){
					DicItem dic = new DicItem();
					dic.setId(dItem.getItemCode());
					dic.setText(dItem.getItemName());
					listDic.add(dic);
					getChild(list,dic);
					flag = false;
				}
		    }
			if(flag){
				if(list.size() > 0){
					int min = list.get(0).getParentCode().toString().length();
					for(int i=1; i<list.size(); i++){
						if(list.get(i).getParentCode().toString().length()<=min){
							min = list.get(i).getParentCode().toString().length();
						}
					}
					for(DictionaryItem dItem : list){
						if(dItem.getParentCode().toString().length() == min){
							DicItem dic = new DicItem();
							dic.setId(dItem.getItemCode());
							dic.setText(dItem.getItemName());
							listDic.add(dic);
							getChild(list,dic);
						}
					}
				}
				
			}
		}
	}	
	public void getChild(List<DictionaryItem> itemList, DicItem dic){
		List<DicItem> dicList = new ArrayList<>();
		for(DictionaryItem dictionaryItem : itemList){
			if(dictionaryItem.getParentCode() != null || "".equals(dictionaryItem.getParentCode())){
				if(dictionaryItem.getParentCode().equals(dic.getId())){
					DicItem dic2 = new DicItem();
					dic2.setId(dictionaryItem.getItemCode());
					dic2.setText(dictionaryItem.getItemName());
					dicList.add(dic2);
					getChild(itemList, dic2);
				}
			}			
		}
		dic.setChildren(dicList);
	}

进入getChild方法是,会重新定义新的dicList集合。递归当dic为001004的时候集合dicList为空。

递归触发提交,当有孩子节点的时候,把当前节点作为父节点,继续调用getChild方法遍历

重新进入getChild方法,当dic为001的时候,集合dicList还是原来的值。

	@Override
	public PageModel<Dictionary> getAllDictionary(ReceiveParameterModel receiveParameterModel) {
		if (receiveParameterModel != null && (receiveParameterModel.getRows() == null  || receiveParameterModel.getPage() == null)) {
			int selectCount = mapper.selectCount(new Dictionary());
			Example example = ExampleUtil.getExample(Dictionary.class, receiveParameterModel);
			List<Dictionary> selectByExample = mapper.selectByExample(example);			
			PageModel<Dictionary> pageModel = new PageModel<>(selectCount,selectByExample);
			return pageModel;
		}else if(receiveParameterModel != null && receiveParameterModel.getPage() != null && receiveParameterModel.getRows() != null){
			PageHelper.startPage(receiveParameterModel.getPage(), receiveParameterModel.getRows());
			Example example = ExampleUtil.getExample(Dictionary.class, receiveParameterModel);
			List<Dictionary> selectByExample = mapper.selectByExample(example);
			//PageInfo<Dictionary> pageInfo = new PageInfo<>(selectByExample);
			return new PageModel<Dictionary>(selectByExample);
		}
		return null;
	}

 

(function (window, $, undefined) {
    var _cache = function () {
        var cache = {};
        this.set = function(dicobj) {
            if ($.util.isObject(dicobj)) {
                if (dicobj !== undefined && dicobj.data !== undefined)
                    $.each(dicobj.data,
                        function(i, n) {
                            var tempitem = cache[i] = cache[i] || {};
                            tempitem.originalData = n;
                            $.each(n,
                                function(j, k) {
                                    //console.log(k);
                                    //k[k.id] = k.text;
                                    if (k.id !== undefined && k.id !== "" && k.text !== undefined)
                                        tempitem[k.id] = k.text;
                                    if (k.children) {
                                        recursiondic(tempitem, k.children);
                                    }

                                });
                        });
            } else {
                throw "字典初始化仅支持对象信息";
            }
        };
        /**
         * 递归子节点
         * @param {any} obj
         * @param {any} children
         */
        function recursiondic(obj, children) {
            $.each(children,
                function (j, k) {
                    //console.log(k);
                    if (k.id !== undefined && k.id !== "" && k.text !== undefined)
                        obj[k.id] = k.text;
                    if (k.children) {
                        recursiondic(obj, k.children);
                    }
                });
        }

        /**
         * 获取字典数据 x.originalData 是原始数据结构 
         * @param {any} dicCode
         */
        this.get = function(dicCode) {
            return $.extend({}, cache[dicCode]);
        };
        /**
         * @param {string} diccodes
         * @param {function} func
         */
        this.initDictionary = function (diccodes, func) {
            $.get("system/dic/getDicByCodes/" + diccodes,
                function (data) {
                    $Core.DicCache.set(data);
                    if (func !== undefined)
                        func(data);
                });
        };
    }
    $Core.DicCache = new _cache();
})(window, jQuery);


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wespten

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

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

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

打赏作者

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

抵扣说明:

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

余额充值