树——子节点链表示

 

父节点表示法是让每个节点记住它的父节点的索引,子节点链是让父节点记住它的所有子节点。

package com.answer.binaryTree;

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

public class TreeChild {
    private static class SonNode{
        private int pos;
        private SonNode next;
        public SonNode(int pos,SonNode next){
            this.pos=pos;
            this.next=next;
        }
    }
    private static class Node{
        private String data;
        private SonNode first;
        public Node(String data){
            this.data=data;
            this.first=null;
        }
    }
    private int DEFAULT_SIZE=16;
    private int treeSize=0;
    private Node[] nodes;
    private int nodeNum;
    public TreeChild(String data){
        this.treeSize=DEFAULT_SIZE;
        nodes=new Node[treeSize];
        nodes[0]=new Node(data);
        nodeNum++;
    }
    public TreeChild(String data,int size){
        this.treeSize=size;
        nodes=new Node[treeSize];
        nodes[0]=new Node(data);
        nodeNum++;
    }
    public void add(String data,Node parent){//向指定节点添加子节点
        for(int i=0;i getChild(Node parent){
        List list=new ArrayList<>();
        SonNode fir=parent.first;
        while(fir!=null){
            list.add(nodes[fir.pos]);
            fir=fir.next;
        }return list;
    }
    public Node child(Node parent,int index){//返回指定父节点的子节点
        SonNode fir=parent.first;
        for(int i=0;fir!=null;i++){
            if(i==index){
                return nodes[fir.pos];
            }
            fir=fir.next;
        }return null;

    }
    public int deep(){
        return deep(root());
    }

    private int deep(Node node) {
        if(node.first==null){
            return 1;
        }else {
            int max=0;
            SonNode fir=node.first;
            while(fir!=null){
                int temp=deep(nodes[fir.pos]);
                if(temp>max){
                    max=temp;
                }
                fir=fir.next;
            }return max+1;
        }
    }
    public int pos(Node node){
        for(int i=0;i list=tree.getChild(root);
        for(Node node:list){
            System.out.println(node.data);
        }
        tree.add("C",list.get(0));
        System.out.println(tree.child(list.get(0),0).data);
        System.out.println(tree.deep());
    }

}

 

你可能感兴趣的:(数据结构)