package com.ywt.mg.core.structs;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by huangguoping.
 */
public class Tree<T extends Serializable> implements Serializable {
    private Node<T> root;
    public Tree(){
        this.root = new Node<>(null);
    }

    public List<Node<T>> getChildren(){
        return this.root.getChildren();
    }

    public Node<T> addChild(T data){
        return this.root.addChild(data);
    }

    public Node<T> root(){
        return this.root;
    }

    public class Node<T extends Serializable> implements Serializable{
        private List<Node<T>> children = null;
        private boolean leaf = true;
        private T data;
        private Node<T> parent;

        public Node(T data){
            this.data = data;
        }
        public Node<T> addChild(T data){
            if (children == null) {
                children = new LinkedList<>();
            }
            Node<T> node = new Node<>(data).setParent(this);
            children.add(node);
            leaf = false;
            return node;
        }

        public T getData(){
            return this.data;
        }

        public boolean isLeaf(){
            return leaf;
        }

        public boolean getLeaf(){
            return leaf;
        }

        public List<Node<T>> getChildren(){
            return this.children;
        }

        public Node<T> parent(){
            return this.parent;
        }
        private Node<T> setParent(Node<T> parent){
            this.parent = parent;
            return this;
        }
    }
}
