首页 > 解决方案 > 从 BST 中删除多余的边缘

问题描述

我有一个 BST,如下所示。如何从 BST 中删除不需要的额外边缘?

1->2, 1->3, 2->4, 2->5, 3->5

应该删除 2->5 或 3->5

 void BFS(int s)
    {
        // Mark all the vertices as not visited(By default
        // set as false)
        boolean visited[] = new boolean[V];

        // Create a queue for BFS
        LinkedList<Integer> queue = new LinkedList<Integer>();

        // Mark the current node as visited and enqueue it
        visited[s]=true;
        queue.add(s);

        while (queue.size() != 0)
        {
            // Dequeue a vertex from queue and print it
            s = queue.poll();
            System.out.print(s+" ");

            // Get all adjacent vertices of the dequeued vertex s
            // If a adjacent has not been visited, then mark it
            // visited and enqueue it
            Iterator<Integer> i = adj[s].listIterator();
            while (i.hasNext())
            {
                int n = i.next();
                if (!visited[n])
                {
                    visited[n] = true;
                    queue.add(n);
                }
            }
        }
    }

标签: javaalgorithm

解决方案


您拥有的不是树,而是有向无环图(DAG):

有向无环图

您正在寻找的算法是生成树算法。找到它的最简单方法之一是先遍历图形深度,并在找到它们时标记图形节点。如果一条边将您带到您已经看到的节点,请删除该边并继续。一旦你完成了深度优先遍历,剩下的图就是一棵树。


推荐阅读