从BST移除额外的边缘

Tej*_*eja 5 java algorithm

我有一个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);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

das*_*ght 8

你拥有的不是一棵树,它是一个有向无环图(DAG):

DAG

您正在寻找的算法是生成树算法.找到它的最简单方法之一是深度优先运行图形,并在找到它们时标记图形节点.如果边缘将您带到已经看过的节点,请删除边缘并继续.完成深度优先行走后,剩下的图形就是一棵树.


小智 1

你想要实现的是一个自平衡二叉树。AVL 树就是这样的一种。Wiki页面有一些注释良好的伪代码,用 Java 实现应该不会太困难。

网络搜索将揭示大量示例。