给定二叉树创建每个深度(BFS或DFS)的所有节点的链表

时间:2015-06-05 05:38:31

标签: java data-structures

我试图找出上述问题的解决方案。我提出了一个解决方案,但我不确定这是否会成功。

public Node LinkedListOfNodes(Node root, Map<Integer, LinkedList<Node>> mapOfLinkedList, int level)
    {

        if(root == null) {
            return null;
        }

        final LinkedList<Node> linkedListOfNodes = new LinkedList();
        level = level+1;

        linkedListOfNodes.add(LinkedListOfNodes(root.left, mapOfLinkedList, level));
        linkedListOfNodes.add(LinkedListOfNodes(root.right,mapOfLinkedList,level));

        mapOfLinkedList.put(level,linkedListOfNodes);

        return root;
    }

这个解决方案对吗?可以采取更好的方法吗? BFS方法可以在这里采用正确的方法,还是DFS可以更好地工作?

这就是我实施BFS的方式。我可以修改它以解决这个问题。

public void BFS(Graph graph, Vertex source) {

        final Queue<Vertex> queue = new PriorityQueue();

        for(Vertex vertex : graph.vertices) {
            vertex.color = "WHITE";
            vertex.distance = 0;
            vertex.parent = null;
        }

        source.distance = 0;
        source.parent = null;
        source.color = "GRAY";

        queue.add(source);

        while(!queue.isEmpty())
        {
            Vertex u = queue.element();
            for (Vertex vertex : graph.adj.get(u))
            {
                if (vertex.color == "WHITE")
                {
                    vertex.color = "GRAY";
                    vertex.distance = vertex.distance + u.distance;
                    vertex.parent = u;

                    queue.add(vertex);
                }
            }

            u.color = "BLACK";
        }

    }


    class Graph {

        List<Vertex> vertices;
        Map<Vertex, List<Vertex>> adj;
    }

    class Vertex {
        int distance;
        Vertex parent;
        String color;
    }

1 个答案:

答案 0 :(得分:3)

以下是一些可以解决问题的代码:

Map<Integer, List<Node>> mapOfLinkedList = new HashMap<Integer, LinkedList<Node>>();

void addNode(Node root, int level) {
    List levelList = mapOfLinkedList.get(level);  // get List for current level
    if (levelList == null) {
        levelList = new LinkedList<Node>();
    }
    levelList.add(root);                          // add Node to the current level

    if (root.left != null) {                      // recursive left call
        addNode(root.left, level+1);
    }
    if (root.right != null) {                     // recursive right call
        addNode(root.right, level+1);
    }

    return;
}

<强>用法:

Node root = new Node();  // populate your tree here
addNode(root, 1);        // make initial call to recursive method here