Recursive Algorithms and Simple Applications

recursive algorithm

A recursive algorithm is a method of solving a problem by repeatedly decomposing it into subproblems of the same kind, and its manifestation is generally the self-invocation of a function. At some point, recursion can be used instead of loops.

To put it simply, the essence of recursion is a behavior in which a function continuously calls itself in its own code.

Of course, we must set a critical value in the process of this circular call, and stop the recursion when the condition is met, otherwise an infinite loop will be formed if the unlimited call continues.

user story

The Municipal Examination Institute wants to organize a city-wide exam. There are about 100 to 200 schools in the city. The simple select selection operation is too cumbersome. Here, it is necessary to select all districts and counties by default. School.

As shown in the figure below, the page is a three-layer tree structure. When a user clicks on a city-level or district-level node, the data I expect to get is that the IDs of all its subordinate schools are stored in an array.
insert image description here
Because the node clicked by the user may be a city-level node, or a district-level node or directly click a school node, so a recursive algorithm can be used here to implement.

// 三层机构树的数据结构大概是这样的:
var data = {
    
    
			 title: '保定市',
		     key: '100',
		     children: [
				{
    
    
					title: '竞秀区',
					key: '1001',
					children: [
						{
    
    
							title: '竞秀一中',
							key: '10011',
							isLeaf: true // isLeaf字段是指示当前节点是否为最下层节点
						},
						{
    
    
							title: '竞秀三中',
							key: '10013',
							isLeaf: true
						}
					]
				},
				{
    
    
					title: '莲池区',
					key: '1002',
					children: [
						{
    
    
							title: '保定一中',
							key: '10021',
							isLeaf: true
						},
						{
    
    
							title: '莲池二中',
							key: '10022',
							isLeaf: true
						}
					]
				}
			]
		};
// 当前选中的学校ID数组
var selectedSchoolIds = [];

// 选中节点的响应事件,参数e是当前选中节点及其下属节点的数据
function getSchoolIds(e){
    
    
	if(e.isLeaf){
    
    
		// 当前节点的isLeaf的值为true时说明当前节点是一个学校节点,需要将其加入到选中列表
		this.selectSchoolIds.push(e.key); 
		// 并且学校节点没有子节点,可以直接借宿递归
		return;
	}
	else
	{
    
    
		// 当前节点没有isLeaf或者isLeaf的值为false,说明当前节点是市级或者区县级节点
		// 但是程序这时候还不能确定是市级还是区县级节点,所以在这里进行递归再进行一次判断
		e.children.foreach((c) => {
    
    
			this.getSchoolIds(c);
		})
	}
}

Guess you like

Origin blog.csdn.net/Dominic_W/article/details/128033378