樹結構

package com;

import java.util.ArrayList;
import java.util.List;

public class Tree {
    //封裝節點
    public List<Node> packagingNode()
    {
        List<Node> listNode = new ArrayList<Node>();
        
        Node a = new Node();
        Node b = new Node();
        Node c = new Node();
        Node d = new Node();
        Node e = new Node();
        Node f = new Node();
        Node j = new Node();
        Node h = new Node();
        Node i = new Node();
        Node g = new Node();
        Node k = new Node();
        Node l = new Node();
        Node m = new Node();
        Node n = new Node();
        
        e.info = "e";
        e.pather = null;
        e.childList.add(j);
        e.childList.add(d);
                
        j.info = "j";
        j.pather = e;
        j.childList.add(i);
        j.childList.add(n);
        j.childList.add(c);
        
        d.info = "d";
        d.pather = e;
        d.childList.add(h);
            
        i.info = "i";
        i.pather = j;
        i.childList.add(f);
    
        n.info = "n";
        n.pather = j;
        n.childList.add(a);
        n.childList.add(b);
    
        c.info = "c";
        c.pather = j;
        
        h.info = "h";
        h.pather = d;
        h.childList.add(m);
        h.childList.add(l);
        h.childList.add(g);
        
        f.info = "f";
        f.pather = i;
        
        a.info = "a";
        a.pather = n;
        a.childList.add(k);
        
        b.info = "b";
        b.pather = n;
        
        m.info = "m";
        m.pather = h;
        
        l.info = "l";
        l.pather = h;
        
        g.info = "g";
        g.pather = h;
        
        k.info = "k";
        k.pather = a;
        
        listNode.add(a);
        listNode.add(b);
        listNode.add(c);
        listNode.add(d);
        listNode.add(e);
        listNode.add(f);
        listNode.add(g);
        listNode.add(h);
        listNode.add(i);
        listNode.add(j);
        listNode.add(k);
        listNode.add(l);
        listNode.add(m);
        listNode.add(n);
        
        return listNode;
    }
    /**
     * 查找樹
     * @param args
     */
    public Node lookNode(String arm){
        List<Node> listNode = this.packagingNode();
        Node nd = null;
        for (Node node : listNode) {
            if(node.info.equals(arm)){
                nd = node;
            }
        }
        return nd;
    }
    public static void main(String[] args) {
        Tree tree = new Tree();
        Node node = tree.lookNode("a");
        System.out.println(node.info);
    }
}

//節點類
class Node{
    public String info;
    public Node pather;
    public List<Node> childList = new ArrayList<Node>();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章