[英]Create Tree Data Structure from Table in Java
給定以下CSV,它表示通用層次結構(請考慮:郵政編碼匿名化,例如,第二步中的郵政編碼46072變為460 ** ):
A1, A*, *
A2, A*, *
A3, A*, *
B1, B*, *
B2, B*, *
B3, B*, *
B4, B*, *
我首先通過解析創建一個數組數組。
我現在想將其轉換為樹表示形式:
*
/ \
A* B*
/ | \ / | | \
A1 A2 A3 B1 B2 B3 B4
如您所見,它是一棵樹,每個節點都有任意數量的子代。
我有以下課程:
Table , TableRow , TableCell以及Tree和Node 。 顯然,一個表具有多個行,而這些行又具有多個單元格。 一棵樹有一個根節點,一個節點有各種操作,例如addChild(node) , getParent() , getChildren()等。
我試圖弄清楚如何遍歷我的桌子,以便跨越一棵樹,如上所示。 到目前為止,我只是讓自己陷入混亂...
非常感謝幫助!
好。 因此,我將基於以下假設做出回答:
我不知道您的表Table,Tree和Node可以做什么或不能做什么。 因此,我使用了一個基本的2d數組(您也說這是解析后的數組),並且僅使用一個基本Node作為我的樹結構。
這個想法是從頭矩陣遞歸地工作。 遞歸和樹結合得很好...
樹被定義為具有最右邊一列中的值作為其根值,並且通過刪除最右邊一列並將矩陣切成小塊以使這些小塊的最右列具有相同的值,以相同的方式創建其子級。 矩陣
A1, A*, *
A2, A*, *
A3, A*, *
B1, B*, *
B2, B*, *
B3, B*, *
B4, B*, *
分為值“ *”和兩個子矩陣:
A1, A*
A2, A*
A3, A*
B1, B*
B2, B*
B3, B*
B4, B*
對A*
矩陣執行相同的操作,其子矩陣為單單元矩陣A1
, A2
和A3
,此時遞歸結束。
因此,假設您創建了一個表示層次結構構建器的類,並且其中有一個名為data
的2D數組,那么您將擁有一個不錯的沒有參數的公共方法,該方法將調用一個“臟”私有方法,該方法具有代表該對象邊界的參數。當前子矩陣的矩陣。
public Node<String> createTree() {
return this.createTree(0,data.length-1,data[0].length-1);
}
它傳遞給private方法的參數是最上一行,最下一行,最左列和最右列。 僅因為在這種情況下,子矩陣始終從列0開始,我們才不需要傳遞最左邊的列作為參數。
這是您的私有createTree
方法:
private Node<String> createTree( int firstRow, int lastRow, int lastCol) {
// Recursion end. If we are at the leftmost column, just return a simple
// node with the value at the current row and column.
if ( lastCol == 0 ) {
return new Node<String>( data[firstRow][0] );
}
// Create a node with the value of the top-right cell in our range.
Node<String> result = new Node<String>(data[firstRow][lastCol]);
// The next column from the right will have the values for the child nodes.
// Split it into ranges (start row -> end row) and recursively build
// the tree over the sub-matrix that goes column 0 -> lastCol-1 over each
// range of rows.
int childFirstRow = firstRow;
String childVal = data[firstRow][lastCol-1];
for( int candidateRow = firstRow; candidateRow <= lastRow; candidateRow ++ ) {
// If the next value in the column is different from what we had so far, it's
// the end of a row range, build the child tree, and mark this row as
// the beginning of the next range.
if ( ! data[candidateRow][lastCol-1].equals(childVal) ) {
result.addChild(createTree( childFirstRow, candidateRow - 1, lastCol - 1));
childFirstRow = candidateRow;
childVal = data[childFirstRow][lastCol-1];
}
// In the special case of the last row, it's always the end of a range.
if ( candidateRow == lastRow ) {
result.addChild(createTree(childFirstRow,lastRow,lastCol - 1));
}
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.