1

我想从左到右打印出一棵树(不是二叉树)中的所有内容。我有以下树类及其方法:

public class Tree
{
    Node root;

    public Tree(String rootData) 
    {
        root = new Node();
        root.data = rootData;
        root.children = new ArrayList<Node>();
    }

    public static class Node
    {
        private String data;
        private Node parent;
        private List<Node> children;

        public Node(){}

        public Node(String newNodeData, Node newNodeParent)
        {
            data = newNodeData;
            parent = newNodeParent;
        }
    }

    public void print(Node curNode)
    {
        int index = 0;
        while(curNode.children.get(index) != null)
        {
            print(curNode.children.get(index));
            System.out.println(curNode.children.get(index).data);
        }
    }

它在该行抛出一个空指针异常,print(curNode.childred.get(index));我不太明白为什么。当print第一次被调用时,树的根节点被传递给它。我是否过度简化了打印方法,还是有更好的方法来做到这一点?我在网上找到的所有东西都是针对二叉搜索树的,我不知道如何让它适用于此。

我也愿意以迭代的方式执行此操作,但我不知道从哪里开始,而且我知道它会比递归执行要复杂得多。或者,如果我说错了,请告诉我。

4

1 回答 1

2

your Node(String newNodeData, Node newNodeParent) constructor does not initialize children, hence its null. you only ever initialize the children array for the root node.

also, when iteratin over children, either compare index to children.getSize() or switch to the newer for(Node n : children) syntax

as a final sidenote - youre accessing Node filds from the Tree constructor. direct field access from a different class is generally frowned upon in java.

于 2013-04-08T00:12:43.800 回答