我有一个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);
}
}
}
}
答案 0 :(得分:6)
你拥有的不是树,它是有向无环图(DAG):
您要查找的算法是Spanning Tree Algorithm。找到它的最简单方法之一是深度优先运行图形,并在找到它们时标记图形节点。如果边缘将您带到已经看过的节点,请删除边缘并继续。完成深度优先行走后,剩下的图形就是一棵树。
答案 1 :(得分:1)
您要实现的是自平衡二叉树。 AVL树就是这样的一种。 Github repo有一些评论很好的伪代码,在Java中实现起来应该非常困难。
网络搜索将揭示大量示例。
答案 2 :(得分:0)
// **Assuming we are maintaining a isVisited flag inside tree node. We can implement this in separate array but for simplicity I assumed it to be inside the node.**
boolean removeBadEdge(Node root) {
if (root == null)
return false;
if (root.left != null && root.left.isVisited)
{
root.left = null; // Removing the bad edge
return true;
}
if (root.right!= null && root.right.isVisited)
{
root.right= null; // Removing the bad edge
return true;
}
root.isVisited = true;
boolean leftEdgeRemoved = removeBadEdge(root.left);
boolean rightEdgeRemoved = false;
if (!leftEdgeRemoved) { // call right only if not removed in left for optimization
rightEdgeRemoved = removeBadEdge(root.right);
}
return leftEdgeRemoved || rightEdgeRemoved;
}