我有一个BST,如下所示.如何从BST中删除不需要的额外边缘?
1-> 1,2-> 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 queue = new LinkedList();
// 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 i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
解决方法:
你拥有的不是树,它是有向无环图(DAG):
您正在寻找的算法是Spanning Tree Algorithm.找到它的最简单方法之一是深度优先运行图形,并在找到它们时标记图形节点.如果边缘将您带到已经看过的节点,请删除边缘并继续.完成深度优先行走后,剩下的图形就是一棵树.
标签:java,algorithm
来源: https://codeday.me/bug/20190527/1162151.html