迭归和迭代是我们在写算法时经常用到的,以下是对迭归几种精典用法的总结:
一,用迭归计算如求1+2+3+...n累加的和
static int demo(int n) {
if (n == 1){
return 1;
}
else{
return n + demo(n - 1);
}
}
二,用迭归遍历如对树形结构的数据遍历
比方说有一数据结构:Category : id,name,pid
将多个Category 放在集合里面,要求找出遍历的父子
String res = "";//对扫描的操作
public String tree(Collection co, int pid) {
Iterator it = co.iterator();
while (it.hasNext()) {
Category ct = it.next();
if (ct.pid == pid) {
int id = ct.id;
// res+=Integer.valueOf(id)+",";
res = ct.name + "的id=" + id + " 其pid=" + pid;
System.out.println(res);
tree(co, id);
}
}
return res;
}
public String tree(Collection co, Category cg) {
Iterator it = co.iterator();
while (it.hasNext()) {
Category ct = it.next();
if (ct.pid == cg.id) {
int id = ct.id;
// res+=Integer.valueOf(id)+",";
res = ct.name + "的id=" + id + " 其pid=" + ct.pid;
System.out.println(res);
// System.out.println(ct);
tree(co, ct);
}
}
return res;
}
public String tree1(List co, Category cg) {
for (int i = 0; i < co.size(); i++) {
Category ct = (Category) co.get(i);
if (ct.pid == cg.id) {
int id = ct.id;
// res+=Integer.valueOf(id)+",";
res = ct.name + "的id=" + id + " 其pid=" + ct.pid;
// System.out.println(res);
System.out.println(ct);
tree(co, ct);
}
}
return res;
}
二,用迭归遍历如对子节点和父节点有共同接口结构的数据遍历
跟java中的设计模式之Composite(组合)很像
Composite定义:
将对象以树形结构组织起来,以达成“部分-整体” 的层次结构,使得客户端对单个对象和组合对象的使用具有一致性.
形如:
public class GenericTreeNode implements TreeNode {
private TreeNode parent = null;
private List> children = new ArrayList>();
public boolean isLeaf() {
return getChildCount() == 0;
}
public boolean isRoot() {
return getParent() == null;
}
。。。
}
方法一:
public void recursiveTravel(GenericTreeNode node) {
System.out.println(node);
//travelNode(node); // 访问节点,迭归扫描的实作操作
List> children = node.getChildren();
for (int i = 0; i < children.size(); i++) {
recursiveTravel(children.get(i)); // 递归地访问当前节点的所有子节点。
}
}
迭归算法的归纳
最新推荐文章于 2025-08-18 11:07:45 发布