树中每个节点的右兄弟节点,以边数组形式给出
给定一棵树,有N个节点和E条边(每条边用两个整数X,Y表示,表示 X 是 Y 的父节点),任务是在单独的行中打印所有节点及其右兄弟节点。
如果特定节点没有正确的兄弟节点,则打印-1 。
例子:
In the image shown above, nodes 3, 5, 6, 7 are the right siblings of nodes 2, 4, 5, 6 respectively and the nodes 1, 3 and 7 have no right siblings.
Input: N = 7, E = 6
edges[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}, {3, 7}}
Output: 1 -1
2 3
3 -1
4 5
5 6
6 7
7 -1
Input: N = 5, E = 4
edges[][] = {{7, 8}, {7, 10}, {7, 15}, {10, 3}}
Output: 7 -1
8 10
10 15
15 -1
3 -1
方法:主要思想是使用广度优先遍历。
- 最初,根节点和“-1”值将被推入队列。在树中特定级别的每个节点都被推送到队列后,必须推送“-1”以确保级别中的最后一个节点没有右兄弟。
- 从队列中弹出每个节点后,队列前面的节点将始终是弹出节点的右兄弟。
- 如果弹出节点的值为'-1',则表示当前级别已被访问,如果队列不为空,则表示该级别的先前节点至少有一个未访问过的子节点。
- 在队列非空时重复上述步骤。
下面是上述方法的实现:
C++
// C++ program to print right siblings
// of all the nodes in a tree
#include
using namespace std;
void PrintSiblings(int root, int N, int E, vector adj[])
{
// boolean array to mark the visited nodes
vector vis(N+1, false);
// queue data structure to implement bfs
queue q;
q.push(root);
q.push(-1);
vis[root] = 1;
while (!q.empty()) {
int node = q.front();
q.pop();
if (node == -1) {
// if queue is empty then
// the popped node is the last node
// no need to push -1.
if (!q.empty())
q.push(-1);
continue;
}
// node and its right sibling
cout << node << " " << q.front() << "\n";
for (auto s : adj[node]) {
if (!vis[s]) {
vis[s] = 1;
q.push(s);
}
}
}
}
// Driver code
int main()
{
// nodes and edges
int N = 7, E = 6;
vector adj[N+1];
// The tree is represented in the form of
// an adjacency list as there can be
// multiple children of a node
adj[1].push_back(2);
adj[1].push_back(3);
adj[2].push_back(4);
adj[2].push_back(5);
adj[3].push_back(6);
adj[3].push_back(7);
int root = 1;
PrintSiblings(root, N, E, adj);
return 0;
}
Java
// Java program to print right siblings
// of all the nodes in a tree
import java.util.*;
class GFG
{
static void PrintSiblings(int root, int N,
int E, Vector adj[])
{
// boolean array to mark the visited nodes
boolean []vis = new boolean[N + 1];
// queue data structure to implement bfs
Queue q = new LinkedList<>();
q.add(root);
q.add(-1);
vis[root] = true;
while (!q.isEmpty())
{
int node = q.peek();
q.remove();
if (node == -1)
{
// if queue is empty then
// the popped node is the last node
// no need to push -1.
if (!q.isEmpty())
q.add(-1);
continue;
}
// node and its right sibling
System.out.print(node + " " +
q.peek() + "\n");
for (Integer s : adj[node])
{
if (!vis[s])
{
vis[s] = true;
q.add(s);
}
}
}
}
// Driver code
public static void main(String[] args)
{
// nodes and edges
int N = 7, E = 6;
Vector []adj = new Vector[N + 1];
for(int i = 0; i < N + 1; i++)
adj[i] = new Vector();
// The tree is represented in the form of
// an adjacency list as there can be
// multiple children of a node
adj[1].add(2);
adj[1].add(3);
adj[2].add(4);
adj[2].add(5);
adj[3].add(6);
adj[3].add(7);
int root = 1;
PrintSiblings(root, N, E, adj);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program to print right
# siblings of all the nodes in
# a tree
def PrintSiblings(root, N, E, adj):
# Boolean array to mark the
# visited nodes
vis = [False for i in range(N + 1)]
# queue data structure to
# implement bfs
q = []
q.append(root)
q.append(-1)
vis[root] = 1
while (len(q) != 0):
node = q[0]
q.pop(0)
if (node == -1):
# If queue is empty then the
# popped node is the last node
# no need to append -1.
if (len(q) != 0):
q.append(-1)
continue
# Node and its right sibling
print(str(node) + " " + str(q[0]))
for s in adj[node]:
if (not vis[s]):
vis[s] = True
q.append(s)
# Driver code
if __name__=='__main__':
# Nodes and edges
N = 7
E = 6
adj = [[] for i in range(N + 1)]
# The tree is represented in the
# form of an adjacency list as
# there can be multiple children
# of a node
adj[1].append(2)
adj[1].append(3)
adj[2].append(4)
adj[2].append(5)
adj[3].append(6)
adj[3].append(7)
root = 1
PrintSiblings(root, N, E, adj)
# This code is contributed by rutvik_56
C#
// C# program to print right siblings
// of all the nodes in a tree
using System;
using System.Collections.Generic;
class GFG
{
static void PrintSiblings(int root, int N,
int E, List []adj)
{
// bool array to mark the visited nodes
bool []vis = new bool[N + 1];
// queue data structure to implement bfs
Queue q = new Queue();
q.Enqueue(root);
q.Enqueue(-1);
vis[root] = true;
while (q.Count != 0)
{
int node = q.Peek();
q.Dequeue();
if (node == -1)
{
// if queue is empty then
// the popped node is the last node
// no need to push -1.
if (q.Count != 0)
q.Enqueue(-1);
continue;
}
// node and its right sibling
Console.Write(node + " " +
q.Peek() + "\n");
foreach (int s in adj[node])
{
if (!vis[s])
{
vis[s] = true;
q.Enqueue(s);
}
}
}
}
// Driver code
public static void Main(String[] args)
{
// nodes and edges
int N = 7, E = 6;
List []adj = new List[N + 1];
for(int i = 0; i < N + 1; i++)
adj[i] = new List();
// The tree is represented in the form of
// an adjacency list as there can be
// multiple children of a node
adj[1].Add(2);
adj[1].Add(3);
adj[2].Add(4);
adj[2].Add(5);
adj[3].Add(6);
adj[3].Add(7);
int root = 1;
PrintSiblings(root, N, E, adj);
}
}
// This code is contributed by Rajput-Ji
Javascript
输出:
1 -1
2 3
3 -1
4 5
5 6
6 7
7 -1