树——父节点表示

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

public class TestTreeparent {
    public class Node{
        private String data;
        private int parent;
        public Node(String data,int parent){
            this.data=data;
            this.parent=parent;
        }
    }
    private int treesize=10;//初始化节点数量
    private Node[] nodes;//建立节点数组存放节点
    private int nodesNumber;//记录节点个数
    public TestTreeparent(String data){
        nodes=new Node[treesize];
        nodes[0]=new Node(data,-1);
        nodesNumber++;
    }
    public int pos(Node node){//返回指定节点的索引
        for(int i=0;i<treesize;i++){
            if(nodes[i]==node){
                return i;
            }
        }
        return -1;
    }
    public void add(String data,Node parent){//根据指定的父节点添加子节点
        for(int i=0;i<treesize;i++){
            if(nodes[i]==null){
                nodes[i]=new Node(data,pos(parent));
                nodesNumber++;
            }
        }
        //throw new RuntimeException("树已满");
    }
    public Node root(){//根节点
        return nodes[0];
    }
    public List<Node> getChild(Node parent){//根据父节点获得子节点
        List<Node> list=new ArrayList<Node>();
        for(int i=0;i<treesize;i++){
            if(nodes[i]!=null&&nodes[i].parent==pos(parent)){
                list.add(nodes[i]);
            }
        }
        return list;
    }
    public int deep(){//树的深度
        int max=0;
        for(int i=0;i<treesize;i++){
            int def=1;
            int father=nodes[i].parent;//父节点索引
            while(father!=-1&&nodes[father]!=null){//父节点存在
                father=nodes[father].parent;//上一层父节点
                def++;
            }
            if(def>max){
                max=def;
            }
        }
        return max;
    }

    public static void main(String[] args) {
        TestTreeparent t=new TestTreeparent("A");
        TestTreeparent.Node root=t.root();
        System.out.println(root.data);
        t.add("fir",root);
        t.add("sec",root);

//        List<Node> zn=t.getChild(root);
//        for(Node n:zn){
//            System.out.println(n.data);
//        }
        System.out.println(t.deep());
    }
}

猜你喜欢

转载自blog.csdn.net/Answer0902/article/details/82227376