我想实现树的数据结构,不是二叉树。有一个根,有n个children,每个child可以有子树。
这个要怎么实现,给点思路啊

解决方案 »

  1.   

    随便写了个,时间紧,只写了个大概,很多方法没写全,参考下吧。package entity;import java.util.ArrayList;
    import java.util.List;public class TreeNode {

    private TreeNode fatherNode = null; private List<TreeNode> childrenNodes = new ArrayList<TreeNode>(); private String nodeName = null; private Object nodeValue = null;

    public boolean hasChildren(){
    return childrenNodes.size() > 0 ? true : false;
    }

    public void removeChildren(int index){
    childrenNodes.remove(index);
    }

    public void removeAllChildren(){
    childrenNodes.clear();
    } public int addChildrenNode(TreeNode childrenNode) {
    childrenNodes.add(childrenNode);
    return childrenNodes.size() - 1;
    } public List<TreeNode> getAllChildrenNodes() {
    return childrenNodes;
    } public String getNodeName() {
    return nodeName;
    } public void setNodeName(String nodeName) {
    this.nodeName = nodeName;
    } public Object getNodeValue() {
    return nodeValue;
    } public void setNodeValue(Object nodeValue) {
    this.nodeValue = nodeValue;
    } public TreeNode getFatherNode() {
    return fatherNode;
    } public void setFatherNode(TreeNode fatherNode) {
    this.fatherNode = fatherNode;
    }


    public static void main(String[] args) {
    TreeNode root = new TreeNode();
    root.setNodeName("根节点");
    root.setNodeValue("四川省");

    TreeNode child1 = new TreeNode();
    child1.setNodeName("子节点");
    child1.setNodeValue("成都市");

    TreeNode child2 = new TreeNode();
    child2.setNodeName("子节点");
    child2.setNodeValue("成华区");

    TreeNode child3 = new TreeNode();
    child3.setNodeName("子节点");
    child3.setNodeValue("金牛区");

    TreeNode child4 = new TreeNode();
    child4.setNodeName("子节点");
    child4.setNodeValue("锦江区");
    //root.a;

    root.addChildrenNode(child1);

    child1.addChildrenNode(child2);
    child1.addChildrenNode(child3);
    child1.addChildrenNode(child4);


    //遍历的时候用根节点开始,用递归往下面遍历,直到节点没有子节点为止。


    }}
      

  2.   

    因为不能改,突然想起两个方法应该改一下。
    public void removeChildren(int index){
    childrenNodes.get(index).setFatherNode(null);
    childrenNodes.remove(index);

    }

    public void removeAllChildren(){
    childrenNodes.clear();
    } public int addChildrenNode(TreeNode childrenNode) {
    childrenNodes.add(childrenNode);
    childrenNode.setFatherNode(this);
    return childrenNodes.size() - 1;
    }