Checking if a node has fully connected neighbours - java

I have a graph and I want to check whether a node has fully connected neighbours. For a node to have fully connected neighbours, all its neighbours must be also be connected.
So, for a node to have fully connected neighbours, the set of its neighbours must be a subset of the set of neighbours of every neighbour of the given node. I have the following code, however it returns false even if it is given a node which does indeed have fully connected neighbours, and I do not see why this is.
public static boolean isFullyConnectedNeighbours(Node node)
{
Set<Node> neighbours = node.neighbours();
for(Node neighbour : neighbours)
{
if(! neighbour.neighbours().containsAll(neighbours)) return false;
}
return true;
}
For a Node, neighbours() returns the set of that node's neighbours

Is it because each node is not a neighbour of itself?
For example...
for(Node neighbour : neighbours)
{
for(Node n2 : neighbours) {
if(neighbour == n2) continue;
if(! neighbour.neighbours().contains(n2)) return false;
}
}
...or something

Related

recursive ordered node coloring

I want to color all nodes of a given graph according to a given node ordering: the order is set through the Iterator<Node> nodeIterator parameter which contains all the nodes to process in the right order.
A node is colored if its neighbor is not and if a certain condition between the two considered nodes is met. A node is colored if it is an element of the parameter vector. A node is colored with its pre-defined color.
here's my code:
#Recursive method colorNodes
colorNodes(Graph graph,Iterator<Node> nodeIterator, Vector vector)
if (vector.size() == graph.size())
return true;
node = nodeIterator.next();
nodeNeighbors = node.getNeighbors();
while(nodeNeighbors.hasnext()) {
neighbor = nodeNeighbors.next();
if (!nodeIsColored(vector, neighbor)) {
if(conditionBetweenNodeAndNeighbor is true) {
vector.add(node) #color current node
colorNodes(graph, nodeIterator,vector)#call recursively the method
}
}
else if (!nodeNeighbors.hasNext()) {
#potential last node or isolated node (having one neighbor only)
if(conditionBetweenNodeAndNeighbor is true) {
vector.add(node) #color last node anyway
colorNodes(graph, nodeIterator,vector)#call recursively the method
}
}
else {
continue;
}
return false;
}
Could anyone clarify how to approach this problem and if my approach is correct (especially the cases differentiation)?
I merely give an answer as the recursion is a bit awkward. I would expect the following - not regarding the logic.
// Recursive method colorNodes
void colorNodes(Graph graph, Iterator<Node> nodeIterator, List<Node> vector)
//if (vector.size() == graph.size())
// return true;
if (!nodeIterator.hasNext()) {
return;
}
Node node = nodeIterator.next();
if (nodeIsColored(vector, node)) {
return;
}
// Here the node is processed before the children, to stop recursion.
​vector.add(node);
for (Node neighbor: node.getNeighbors()) {
//if (!nodeIsColored(vector, neighbor)) {
colorNodes(graph, nodeIterator,vector);
//}
}
// Here the node could be processed after the children.
}
Vector<> is the old class, and still lives under that name in for instance C++.
I am not sure I fully understood the requirement. Please check this pseudo code:
//Recursive method colorNodes
colorNodes(Graph graph,Iterator<Node> nodeIterator, Vector vector){
if (vector.size() == graph.size()) return true;
node = nodeIterator.next();
neighbors = node.getNeighbors()
//check if leaf or isolted or all neigbors colored
if( (! nodeIterator.hasNext()) or (neighbor.length == 0) or (allNodesAreColored(neighbors)) ) {
//color leaf
if(conditionBetweenNodeAndNeighbor is true) {
vector.add(node)
node.setColor(color)
// no need for recursive call for a leaf
}
return;
}
for(neighbor : neighbors ){
if ((!nodeIsColored(vector, neighbor) and
(conditionBetweenNodeAndNeighbor is true) ){
vector.add(node)
node.setColor(color)
colorNodes(graph, nodeIterator,vector)
//break if you don't want to check rest of the neighbors
}
}
}

Recursive inorder Successor of a given element in BST with java

Because the code is too long the link is here ->http://pastebin.com/jXgbE6bB
Because i am not that good at recursions i just can't find the right recursion function for this problem.
(P.S.I am new to this forum and i know i am going to have a lot of hate comments like why not go find tutorials on recursions and other things,but believe me i have done everything but i just can't understand the logic of the recursions)
My question is What's the recursive function for in-order successor of a given element in Binary search tree?I made it this far but it just returns the parent of the node it's supposed to print:
public E getSuccessor(BNode<E> t, E x) {
if(t.left!=null && x.equals(t.info)){
return t.left.info;
}
else if(x.compareTo(t.info)<0){
return (getSuccessor(t.left, x));
}
else {
return (getSuccessor(t.right, x));
}
}
public E getSuccessor(E x) {
return getSuccessor(root, x);
}
The inorder successor of a given node is the lowest node in the right subtree of that node. To understand otherwise, it is the next node that will be printed in a simple in order traversal of the tree.
If the node has a right child, this solution is simplified to finding the smallest node in the right subtree.
If the node doesn't have a right child, and there are no parent pointers, we need to start from the root of the tree and work our way to identify this successor.
Here is the recursive way to solve this. While calling the method, pass root as the root of the tree, the node who's successor is needed as t and null as the successor because the method will calculate it. Something like the following -
BinaryTreeNode successor=tree.inorderSuccessor(root,node,null);
public BinaryTreeNode<Type> inorderSuccessor(BinaryTreeNode<Type> root,BinaryTreeNode<Type> t,BinaryTreeNode<Type> successor)
{
if(root==null)
return null;
if(root.element==t.element)
{
if(root.right!=null)
return findMin(root.right);
else
return successor;
}
int cmp=t.element.compareTo(root.element);
if(cmp < 0)
return inorderSuccessor(root.left,t,root);
else
return inorderSuccessor(root.right,t,successor);
}
public BinaryTreeNode<Type> findMin(BinaryTreeNode<Type> t)
{
if(t==null)
return t;
while(t.left!=null)
t=t.left;
return t;
}

How to find the next in order successor in a binary tree?

I'm trying to implement an Iterator in my own TreeSet class.
However my attempt at creating it only works until the current node is the root.
The Iterator looks like this:
Constructor:
public TreeWordSetIterator()
{
next = root;
if(next == null)
return;
while(next.left != null)
next = next.left;
}
hasNext:
public boolean hasNext()
{
return next != null;
}
Next:
public TreeNode next()
{
if(!hasNext()) throw new NoSuchElementException();
TreeNode current = next;
next = findNext(next); // find next node
return current;
}
findNext:
private TreeNode findNext(TreeNode node)
{
if(node.right != null)
{
node = node.right;
while(node.left != null)
node = node.left;
return node;
}
else
{
if(node.parent == null)
return null;
while(node.parent != null && node.parent.left != node)
node = node.parent;
return node;
}
}
This works fine up until I get to my root node. So I can only iterate through the left child of root, not the right. Can anyone give me a few tips on what I'm doing wrong? I don't expect a solution, just a few tips.
Question: How can I find the next node in a TreeSet given each node points to its parent, left-child and right-child.
Thanks in advance
It helps to consider the rules of a Binary Search Tree. Let's suppose the previously returned node is n:
If n has a right subtree, then the node with the next value will be the leftmost node of the right subtree.
If n does not have a right subtree, then the node with the next value will be the first ancestor of n that contains n in its left subtree.
Your code is correctly handling the first case, but not the second. Consider the case where node is the leftmost leaf of the tree (the starting case). node has no right child, so we go straight to the else. node has a parent, so the if-clause is skipped. node.parent.left == node, so the while clause is skipped without executing at all. The end result is that node gets returned. I'd expect your iterator to continue returning the same node forever.
There are 3 main ways you can iterate a binarry tree
private void inOrder(TreeNode node) {
if(isEmpty())return;
if(node.getLeftNode()!=null)inOrder(node.getLeftNode());
System.out.print(node.getNodeData()+" ");
if(node.getRightNode()!=null)inOrder(node.getRightNode());
}
private void preOrder(TreeNode node) {
if(isEmpty())return;
System.out.print(node.getNodeData()+" ");
if(node.getLeftNode()!=null)preOrder(node.getLeftNode());
if(node.getRightNode()!=null)preOrder(node.getRightNode());
}
private void postOrder(TreeNode node) {
if(isEmpty())return;
if(node.getLeftNode()!=null)postOrder(node.getLeftNode());
if(node.getRightNode()!=null)postOrder(node.getRightNode());
System.out.print(node.getNodeData()+" ");
}
//use
inOrder(root);
preOrder(root);
postOrder(root);
Its simple as that ,your code doesn't really makes sense to me, is there something else you are trying to do besides iterating in one of this ways?
I think you need to save previous point in your iterator so you know where you've been before
Here some code but be aware that it is not complete you should do it by yourself and it's just to show you the idea. it also doesn't handle the root node.
findNext(TreeNode node, TreeNode previousNode) {
if(node.left != null && node.left != previousNode && node.right != previousNode){ //go left if not been there yet
return node.left;
}
if(node.right != null && node.right != previousNode){ //go right if not been there yet
return node.right;
}
return findNext(node.parent, node); //go up and pass current node to avoid going down
}
A good approach is to use a stack to manage sequencing, which is sort of done for you if you use a recursive traversal (instead of trying to build an Iterator at all) as described in SteveL's answer.
As you want to start from the left, you first load onto the stack the root node and its leftmost children in the proper order (push while going down to the left from the root).
Always pop the next from the top of the stack, and push its right child (if any) and all its leftmost children before returning the one you just popped, so that they're next in line.
By this approach, the top of the stack will always be the next to return, and when the stack is empty, there's no more...
In code:
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;
public class TreeNodeInOrderIterator<T> implements Iterator<T> {
private final Stack<TreeNode<T>> stack;
public TreeNodeInOrderIterator(TreeNode<T> root) {
this.stack = new Stack<TreeNode<T>>();
pushLeftChildren(root);
}
#Override
public boolean hasNext() {
return !stack.isEmpty();
}
#Override
public T next() {
if (!hasNext())
throw new NoSuchElementException();
TreeNode<T> top = stack.pop();
pushLeftChildren(top.right);
return top.val;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
private void pushLeftChildren(TreeNode<T> cur) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
}
}
In this code, TreeNode is defined by
public class TreeNode<T> {
T val;
TreeNode<T> left;
TreeNode<T> right;
TreeNode(T x) { val = x; }
}
If you want to have each node also know its parent, that's ok, but all the traversal is by using what's on the stack and adding to the stack using the left and right child links.

Find path to node in Tree?

I have a tree class that looks like:
Class Tree {
Node root;
Node curNode;
public List<String> find(String value) {
if (curNode == null) curNode = root;
for (Node child : curNode.children) {
if (found == false) {
if (child.data.equals(value)) {
// if it finds it return the path to this node.
}
curNode = child;
findDFS(value);
}
}
}
class Node {
List<Node> children;
String data;
}
Where the tree root contains pointers to children nodes which point to other children etc etc. What I'm having problems with is once it finds the node, I need to return the the path to that node.
passing a list tracking the path, once find the node, exit the recursion and fill the path one by one.
Boolean Search(Node node, String value, List<Node> track)
{
if (node == null) return false;
if (node.data.equals(value))
{
track.add(node);
return true;
}
for(Node child : node.children)
{
if (Search(child, value, track)
{
track.add(0, node);
return true;
}
}
return false;
}
If the nodes only point to their children, you'll need to keep track of each path on the way down. As mentioned in comment, you can do this with your own stack or with recursion. For example, you could always return find() call on the children of each node.
If the nodes point both ways, you can easily re-trace the path up once you find the correct node.
The following code traces the path, adding nodes to the list and removing them if they are not in the path
boolean getPath(Node root,String targetValue,List<Integer> path)
{
// base case root is null so path not available
if(root==null)
return false;
//add the data to the path
path.add(root.getData());
//if the root has data return true,path already saved
if(root.getData().equals(targetValue))
return true;
//find the value in all the children
for(Node child: children){
if(getPath(child,targetValue,path))
return true;
}
//if this node does not exist in path remove it
path.remove(path.size()-1);
return false;
}

Remove the minimum value in a binary search tree

I understand the algorithms but I am not sure how to put it into actual codes. Please help! And also please explain in details. I really want to understand this besides just copying down the answer. ;)
Here are my codes:
public boolean getLeftChild(){
Node insertNode = root;
while(insertNode!=null){
insertNode = insertNode.left;
}
return true;
}
public Boolean removeMin(){
Node insertNode = root;
Node parentNode =root;
if (insertNode.left ==null){
insertNode.right = parentNode;
insertNode = null;
}else if (getLeftChild() ==true && insertNode.right != null){
insertNode.left = null;
}else{
parentNode.left = insertNode.right;
}
return true;
}
First things first: For trees I highly recommend recursion.
Just one example:
getSmallestNode(Node node){
if(node.left != null){
return getSmallestNode(node.left)
}
return node;
}
For the deletion, there can be two cases if you want do delete the smallest (and therefore the "most left leaf" child) of a binary tree.
Case 1: The leaf has no child nodes, in that case just set the according entry in the parent to null (mostLeftChild.getParent().left = null)
Case 2: The leaf has a right child node (there can't be a left child node because that means there would be a smaller node and your currently selected node isn't the smallest) in that case you replace the current left node with the smallest node of the right subtree mostLeftChild.getParent().left = getSmallestFromSubtree(mostLeftChild.right)
So now to make that into code, it could look something like this (No guarantee that it really works)
public Node deleteSmallest(Node node){
// haven't reached leaf yet
if(node.left != null{
return deleteSmallest(node.left)
}
// case 1, no child nodes
if(node.right == null){
node.getParent().left = null;
} else { // case 2, right child node
node.getParent().left = deleteSmallest(node.right)
}
return node;
}
And you would call it with deleteSmallest(root)

Categories

Resources