一、遞歸
在編程中,程序調用自身的編程技巧稱之爲遞歸。滿足遞歸編程首先需要具備兩個條件:
1.子問題與原始問題爲同樣的事,且更爲簡單。
2.不能無限制的調用本身,必須有一個出口。
其實在網上,我們能收到很多關於遞歸編程的例子。例如累加,階乘等。下面我們先用一個階乘的例子來簡單說明遞歸,後面我將介紹一個在實際開發中我用(遞歸+dom4j實現樹的遍歷)實踐過的一個遞歸編程實例。
二、階乘實例
在數學中,我們會計算一個數的階乘是多少?在這裏就不介紹階乘了,簡單來說就是n!=1*2*3*4...*(n-1)*n.
在用程序實現計算一個階乘時,我們可以套用遞歸的概念。階乘就是一個數不斷減1相乘,直到1爲止。
根據遞歸條件1,子問題與原始問題爲同樣的事,這裏階乘是數不斷減1相乘(滿足)。
而且遞歸不能無限循環,需要有一個出口,階乘是到1爲止(滿足)。
所以階乘是完全可以用遞歸編程技巧來實現的,好,那我們就來寫一個吧。
public class Caculate {
public static void main(String[] args) {
Integer x=jicheng(10);
System.out.println(x);
}
public static Integer jicheng(Integer n){
if (n==1) {
return n;
}else{
return n*jicheng(n-1);
}
}
}
運行結果
public static void main(String[] args) {
Integer x=jicheng(6);
System.out.println(x);
}
public static Integer jicheng(Integer n){
if (n==1) {
return n;
}else{
return n*jicheng(n-1);
}
}
}
運行結果:
720
三、實戰演練(遞歸+dom4j)實現樹的遍歷並輸出XML。
在生產環境中,我們很可能遇到如下圖的樹狀結構。例如組織,部門,角色等樹狀結構。在這些結構中,如果我們要查詢某一組織下所有的子組織,並用XML格式輸出。
//編程方法
public void addTreeNode(String pid,Element parentElement){
Element childElement=parentElement.addElement("ORG");
Organization childOrg=findTreeNodeById(pid);
Element childElementName=parentElement.addElement("NAME");
childElementName.addText(childOrg.getName());
Element childElementID=parentElement.addElement("ID");
childElementID.addText(childOrg.getId());
List<Organization> childElements=findChildTreesNodeById(pid);
if (childElements!=null&&childElements.size>0) {
Element childsElement=parentElement.addElement("ORGS");
for (int i = 0; i < childElements.size(); i++) {
addTreeNode(childElements.get(i).getId(), childsElement);
}
}
}
輸出結果:
<ORG>
<NAME>組織結構</NAME>
<ID>1</ID>
<ORGS>
<ORG>
<NAME>組織結構1</NAME>
<ID>2</ID>
</ORG>
<ORG>
<NAME>組織結構2</NAME>
<ID>3</ID>
</ORG>
<ORG>
<NAME>組織結構3</NAME>
<ID>4</ID>
</ORG>
</ORGS>
<ORG>