我們有這個班
public class A {
private String someVariable;
private List<A> innerObjects;
/**
* setters & getters...
*
*/
}
假設我們不知道 innerObjects 內部有多少物件,我們如何以最佳方式手動迭代該物件?主要問題將在內部串列上,因為它可能還有另一個串列,另一個串列,另一個串列等等......
uj5u.com熱心網友回復:
要訪問每個嵌套節點,您可以進行樹遍歷。有幾種遍歷順序可供選擇:
- 深度優先,預購
- 深度優先,后序
- 廣度優先
- ...
以下是這些字串的深度優先、預排序列印someVariable的一些示例代碼,每個都按樹中的深度縮進,以及另一個執行整個物件結構的深層復制的函式:
import java.util.*;
public class A {
private String someVariable;
private List<A> innerObjects;
public A(String text) {
someVariable = text;
innerObjects = new ArrayList<A>();
}
public A add(String text) {
return add(new A(text));
}
public A add(A object) {
innerObjects.add(object);
return object;
}
public A deepCopy() {
A object = new A(someVariable);
for (A inner : innerObjects) {
object.add(inner.deepCopy());
}
return object;
}
public void deepPrint() {
deepPrint("");
}
public void deepPrint(String prefix) {
System.out.println(prefix someVariable);
for (A object : innerObjects) {
object.deepPrint(prefix " ");
}
}
}
還有一些驅動程式代碼來測驗這個:
public static void main(String[] args) {
A root = new A("world");
A europe = root.add("Europe");
europe.add("Germany");
europe.add("France");
A northAmerica = root.add("North America");
northAmerica.add("United States");
northAmerica.add("Canada");
A copy = root.deepCopy();
copy.deepPrint();
}
uj5u.com熱心網友回復:
O(n)您肯定無法更有效地迭代串列。
因此,您可以創建一個方法來迭代串列并執行某些操作(基本上您甚至可以在那里提供一個實作業務邏輯的函式),如果內部 A包含一個串列,則再次遞回呼叫物件上的方法
這種方法的一個簡單示例可能是:
String concatenateAllVariables(String current) {
if(innerObjects != null) { // this and the fact loop won't start when the list will be empty is our "stop condition"
for(A a: innerObjects) {
current = a.concatenateAllVariables(""); // this is recursive call
}
}
current = someVariable; // where this line (before or after processing children) shoud be is due to traversal algorithm
return current;
}
另請閱讀:
- 什么是遞回
- Java 傳遞方法作為引數
- 遍歷 Java 中二叉樹的所有節點- 因為通常您可以將每個
A實體視為一些抽象樹節點,并將它的串列視為子節點(這種結構看起來有點像B-tree)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411540.html
標籤:
上一篇:CountNiceSubarrays-了解滑動視窗技術而不是前綴總和
下一篇:完全二叉樹時間復雜度
