學習Java的同學注意了!!!
學習進程中遇到甚么問題或想獲得學習資源的話,歡迎加入Java學習交換群,群號碼:183993990 我們1起學Java!
簡單的實現了1個樹的結構,很不完善!后續參考1些其他代碼的實現。
試圖實現葉子存在可變的節點,能夠用來解析xml文件。
葉子的代碼:
1 package com.app; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class treeNode<T> { 7 public T t; 8 private treeNode<T> parent; 9 10 public List<treeNode<T>> nodelist; 11 12 public treeNode(T stype){ 13 t = stype; 14 parent = null; 15 nodelist = new ArrayList<treeNode<T>>(); 16 } 17 18 public treeNode<T> getParent() { 19 return parent; 20 } 21 }
樹的代碼:
1 package com.app; 2 3 public class tree<T> { 4 5 public treeNode<T> root; 6 7 public tree(){} 8 9 public void addNode(treeNode<T> node, T newNode){ 10 //增加根節點 11 if(null == node){ 12 if(null == root){ 13 root = new treeNode(newNode); 14 } 15 }else{ 16 treeNode<T> temp = new treeNode(newNode); 17 node.nodelist.add(temp); 18 } 19 } 20 21 /* 查找newNode這個節點 */ 22 public treeNode<T> search(treeNode<T> input, T newNode){ 23 24 treeNode<T> temp = null; 25 26 if(input.t.equals(newNode)){ 27 return input; 28 } 29 30 for(int i = 0; i < input.nodelist.size(); i++){ 31 32 temp = search(input.nodelist.get(i), newNode); 33 34 if(null != temp){ 35 break; 36 } 37 } 38 39 return temp; 40 } 41 42 public treeNode<T> getNode(T newNode){ 43 return search(root, newNode); 44 } 45 46 public void showNode(treeNode<T> node){ 47 if(null != node){ 48 //循環遍歷node的節點 49 System.out.println(node.t.toString()); 50 51 for(int i = 0; i < node.nodelist.size(); i++){ 52 showNode(node.nodelist.get(i)); 53 } 54 } 55 } 56 }
測試的主函數:
1 package com.app; 2 3 public class app { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 /*簡單實現1個樹的結構,后續完善解析xml */ 11 /*寫得滿爛的,后續查閱1些其他代碼 2012⑶⑴2 */ 12 //測試 13 /* 14 * string 15 * hello 16 * sinny 17 * fredric 18 * world 19 * Hi 20 * York 21 * */ 22 23 tree<String> tree = new tree(); 24 tree.addNode(null, "string"); 25 tree.addNode(tree.getNode("string"), "hello"); 26 tree.addNode(tree.getNode("string"), "world"); 27 tree.addNode(tree.getNode("hello"), "sinny"); 28 tree.addNode(tree.getNode("hello"), "fredric"); 29 tree.addNode(tree.getNode("world"), "Hi"); 30 tree.addNode(tree.getNode("world"), "York"); 31 tree.showNode(tree.root); 32 33 System.out.println("end of the test"); 34 } 35 36 }
學習Java的同學注意了!!!
學習進程中遇到甚么問題或想獲得學習資源的話,歡迎加入Java學習交換群,群號碼:183993990 我們1起學Java!