简单的实现了一个树的结构,很不完善!后续参考一些其他代码的实现。
试图实现叶子存在可变的节点,能够用来解析xml文件。
叶子的代码:
View Code
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 }
树的代码:
View Code
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 }
测试的主函数:
View Code
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 /*简单实现一个树的结构,后续完善解析xml */
11 /*写得满烂的,后续查阅一些其他代码 2012-3-12 */
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 }