我遇到了一个问题,那就是从主 node 获取所有sibling node ,并实现Java编写的进程n广度优先搜索算法.
我如何才能实现这一点?
我分享了我的代码片段,如下所示.
下面是我的Node类,如下所示.
public class Node{
Node(int data){
this.data = data;
this.left = null;
this.right = null;
this.visited = false;
}
int data;
Node left;
Node right;
boolean visited;
// getter and setter
}
下面是如下所示的初始化过程.
Node node1 = new Node(1);
Node node7 = new Node(7);
Node node9 = new Node(9);
Node node8 = new Node(8);
Node node2 = new Node(2);
Node node3 = new Node(3);
node1.left = node7;
node1.right = node9;
node7.right = node8;
node9.right = node3;
node9.left = node2;
下面是显示的方法.
public static void bfs(Node root){
if (root == null){
return;
}
Node temp; //a binary tree with a inner generic node class
Queue<Node> queue = new LinkedList<>(); //can't instantiate a Queue since abstract, so use LLQueue
queue.add(root);
root.visited = true;
while (!queue.isEmpty())
{
temp = queue.poll(); //remove the node from the queue
// How can I get all siblings of the node like
// for (Node sibling : temp.getSiblingNodes())
// sibling.visited=true;
// queue.add(sibling);
}
// get the result as a list
}