Java簡單實現樹
阿新 • • 發佈:2019-02-20
import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class LinkedTreeNode { private Object data; // 儲存的資料 private LinkedTreeNode parentNode; // 雙親節點 private List<LinkedTreeNode> childList; // 孩子節點的引用 public LinkedTreeNode(Object data, LinkedTreeNode parent) { this.data = data; parentNode = parent; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public Object getParent() { return parentNode; } public void setParent(LinkedTreeNode parent) { parentNode = parent; } public List<LinkedTreeNode> getChild() { return childList; } public void setChild(List<LinkedTreeNode> childList) { this.childList = childList; } public static void main(String[] args) { //建立根節點 LinkedTreeNode rootNode = new LinkedTreeNode("root", null); //新增孩子節點 LinkedList<LinkedTreeNode> childList = new LinkedList<LinkedTreeNode>(); LinkedTreeNode child1 = new LinkedTreeNode("child1", rootNode); LinkedTreeNode child2 = new LinkedTreeNode("child2", rootNode); childList.add(child1); childList.add(child2); rootNode.setChild(childList); //輸出根節點資料 System.out.println(rootNode.getData()); //輸出孩子節點的資訊 Iterator<LinkedTreeNode> iter = rootNode.getChild().iterator(); while (iter.hasNext()) { System.out.println(iter.next().getData()); } } }