java删除边_java – 从BST中删除额外的边缘

我有一个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):

Bm3Rx.png

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

标签:java,algorithm

来源: https://codeday.me/bug/20190527/1162151.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值