recursive ordered node coloring - java

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
}
}
}

Related

Checking if a node has fully connected neighbours

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

Equivalent subtree

I have two trees. The tree Node is defined as
class Node{
String treeId;
String type; //Each node has type which has fixed value. For example, its color: RED, BLANK, GREEN
Set<Node> children;
String ref; //The ref is a string and allowed value are "0", "1",..."10". The value is null if it is not leaf.
};
For leaf, the children set is empty.
I am wondering whether there is some existing efficient work done how to identify equivalent substree for two given tree. The equivalent is defined as:
1) Both subtree leaves are setsets leaves of original tree.
2) Both subtrees leaves have same ref value.
3) for non-leaves node, the equivalent refers to both node have same type and equivalent children.
Thanks. It would be better if there is some Java library addressing this problem.
The input should are two tree roots while output is the Node that is root of equivalent subtree. An the the tree's height is 100~ and it has more than 500 nodes.
What i did now is that I added a new field for class Node.
class Cache{
Map<String, Set<String>> map = new LinkedHashMap<String, Set<Str>>();
}
The key of map is Node id while the value is a ref set this node of this nodeid can reach. The Cache initiated when Node is initialized.
During isEquivalent compare phase, check whether overlap exists between two root's ref set. Return false if none.
I think this can help reduce the number of comparison space.
I am not sure about 1) Both subtree leaves are leaves of original tree. requirement as it seems to conflict with how to identify equivalent substree for two given tree.. Otherwise following recursive method should be able to cover other two conditions. The haveSameOriginalTree(r1, r2) method may be implemented to satisfy the first condition that I couldn't understand. r1 and r2 are roots of two subtrees that need to be checked for equivalence.
bool areEquivalent(Node r1, Node r2)
{
if(r1.children == null && r2.children == null)
{
return (haveSameOriginalTree(r1, r2) && (r1.ref == r2.ref));
}
if((r1.children == null && r2.children != null) || (r1.children != null && r2.children == null))
{
return false;
}
// if here then both must be non-leaf nodes
if(r1.type != r2.type)
{
return false;
}
if(r1.children.getCount() != r2.children.getCount()) // not sure of correct syntax for Java Sets
{
return false;
}
for(int i=0; i<r1.children.getCount(); i++)
{
if(!areEquivalent(r1.children[i], r2.children[i])) // again please correct the syntax for Sets
{
return false;
}
}
return true;
}
Let me know what you think.
Update
Here is an iterative version of the above solution. It uses stack data structure which is allocated on the heap rather than pushed on function's call stack, so not hugely different from recursive but still better. Also, since we only hold references to Nodes (rather than copying the whole object), this shouldn't be that much of an additional memory overhead if we are already loading the original tree into memory.
bool areEquivalent(Node r1, Node r2)
{
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
Node n1, n2;
s1.Push(r1);
s2.Push(r2);
while(true) // Need a better check
{
if(s1.getCount() != s2.getCount())
{
return false;
}
if(s1.getCount() == 0) // if both stacks are empty then we've traversed both trees without failure.
{
return true;
}
n1 = s1.Pop();
n2 = s2.Pop();
if(!areEquivalentNodes(n1, n2))
{
return false;
}
foreach(Node child in n1.children)
{
s1.Push(child);
}
foreach(Node child in n2.children)
{
s2.Push(child);
}
}
}
// only checks the two nodes are equivalent. their childrens' equivalence will be handled by other calls to this method.
bool areEquivalentNodes(Node n1, Node n2)
{
if(n1.children.getCount() != n2.children.getCount())
{
return false;
}
if(n1.children.getCount() == 0) // if both are leaf nodes...
{
if(n1.ref != n2.ref)
{
return false;
}
}
else // both are non-leaf
{
if(n1.type != n2.type)
{
return false;
}
// the condition that children of non-leaf nodes be equivalent will be covered by subsequent calls this method...
}
return true;
}
Please note that both solutions expect children of two equivalent nodes in the same order. If children are not ordered then we will need to sort them before calling above code.
Let me know if this is better.

How to "delete" a node from a binary search tree in Java?

I made a binary search tree in Java but I'm having troubles whit the deleting nodes part. I managed to erase the node when it has only 1 son, and I have the idea to make the deletion when it has 2 sons, anyways the method I'm using when it has no sons (when it's a leaf) is not working in Java. Normally in C++ I would assign the Node "null" but it doesn't work here.
if (numberOfSons(node) == 0) {
node= null;
return true;
}
That's the portion of the code that takes care of the nulling part. When I debug it, it is referencing the correct node and it's assigning it the null value, but when I return to the Frame where I'm calling the delete method for my tree the node is still there. What's the correct way to "null" an object in Java? I thought everything was a pointer in here and therefore this would work, but I think it doesn't.
When you're nulling something you just make the reference in the scope you're in null. It doesn't affect anything outside.
Let me explain by example. Say you have a method foo:
public void foo(Node node) {
node = null;
if(node == null) {
System.out.println("node is null");
} else {
System.out.println("node is not null");
}
}
Now you call it like this:
public void doSomething() {
Node node = new Node();
foo(node);
if(node == null) {
System.out.println("Original node is null");
} else {
System.out.println("Original node is not null");
}
}
In your console you'll get:
node is null
original node in not null
The reason is that it's not a pointer, it's a reference. When you're nulling a reference, you just say "make this reference synonym to null". It doesn't mean that the object is deleted, it may still exist in other places. There is no way to delete objects in java. All you can do is make sure no other object points to them, and the garbage collector will delete the objects (sometime).
Nothing remains but to reinsert either left or right subtree. For instance:
class BinaryTree<T extends Comparable<T>> {
class Node {
Node left;
Node right;
T value;
}
Node root;
void delete(T soughtValue) {
root = deleteRec(root, soughtValue);
}
Node deleteRec(Node node, T soughtValue) {
if (node == null) {
return null;
}
int comparison = soughtValue.compareTo(node.value);
if (comparison < 0) {
node.left = deleteRec(node.left, soughtValue);
} else if (comparison > 0) {
node.right = deleteRec(node.right, soughtValue);
} else {
if (node.left == null) {
return node.right;
} else if (node.right == null) {
return node.left;
} else {
// Two subtrees remain, do for instance:
// Return left, with its greatest element getting
// the right subtree.
Node leftsRightmost = node.left;
while (leftsRightmost.right != null) {
leftsRightmost = leftsRightmost.right;
}
leftsRightmost.right = node.right;
return node.left;
}
}
return node;
}
}
As Java does not have aliases parameters as in C++ Node*& - a kind of in-out parameter, I use the result of deleteRec here. In java any function argument that is an object variable will never change the variable with another object instance. That was one of the language design decisions like single inheritance.

Adding an element a binary search tree

Trying to add an element to BST. I have an idea of how to do it, but my implementation is destructive, and the original root is not preserved (so the tree basically becomes useless). The tree is based on lists, and this method is based on recursion. My real problem is preserving the original root. I'm using generics.
So far what I have:
public void addElement(E elem, Node<E> root) {
Create node with a value of elem, call it newNode
Case 1: Tree is empty
root = newNode();
return; //End of method.
Otherwise, keep searching the tree (by comparing the value of out node a with the root of the tree.
if (!root.hasLeft() && !root.hasRight) { //if the root in question has no children
if (elem < rootValue) { //Set the element as the left element
root.setLeft(newNode);
}
else { //Set the element as the right element.
root.setRight(newNode);
}
}
else {
if (E < root.getElem()) {
//This is where the value of our node is compared to the value of the root, which we passed in.
//(I know that we can't use the < and > operators with generics, but assume it works).
root = root.getLeft() //Left node is new root
addElement(elem, root); //Call the method again
}
else {
root = root.getRight(); //Right node is new root
addElement(elem, root) //Call method again
}
}
}
Forgive me if this is a duplicate/vague question, this is my first post on SO, and I'm kind of noob.
if (!root.hasLeft() && !root.hasRight) {
This logic is wrong. You're only considering "setting" the left child, if you have neither a left nor right child. This change should do it:
void addElement(elem, root)
{
if (elem < root.value) {
if(!root.hasLeft())
root.setLeft(newNode);
else
addElement(elem, root.getLeft());
}
else {
if(!root.hasRight())
root.setRight(newNode);
else
addElement(elem, root.getRight());
}
}
You should not be changing root of the class, just passing it into the next method call. This should preserve root.
By the way, I assume you have rootValue = root.value somewhere or somethign similar?

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