Is it necessary to distinguish 3 state fields when doing breadth first search - algorithm

In the CTCI solution for checking to see if there is a route between two nodes, a 3 state enum is defined. However, it appears that what is really important is a binary state of (visited = true|false). Is this true? If not, why is it necessary to distinguish between 3 separate states?
public enum State {
Unvisited, Visited, Visiting;
}
public static boolean search(Graph g,Node start,Node end) {
LinkedList<Node> q = new LinkedList<Node>();
for (Node u : g.getNodes()) {
u.state = State.Unvisited;
}
start.state = State.Visiting;
q.add(start);
Node u;
while(!q.isEmpty()) {
u = q.removeFirst();
if (u != null) {
for (Node v : u.getAdjacent()) {
if (v.state == State.Unvisited) {
if (v == end) {
return true;
} else {
v.state = State.Visiting;
q.add(v);
}
}
}
u.state = State.Visited;
}
}
return false;
}

Related

Modifying depth-first search

(source, destination) and it's type (tree, back, forward, cross)?
Here you go. Code in Java
import java.util.ArrayList;
import java.util.List;
class Node {
public String name;
public List<Node> connections = new ArrayList<>();
boolean visited = false;
Node(String name) {
this.name = name;
}
}
class DFS {
// Main part.
public static void search(Node root) {
if (root == null) {
return;
}
root.visited = true;
for (Node node : root.connections) {
if (!node.visited) {
// Print result.
System.out.println(root.name + "->" + node.name);
search(node);
}
}
}
}
public class App {
public static void main(String[] args) {
Node a = new Node("a");
Node b = new Node("b");
Node c = new Node("c");
Node d = new Node("d");
Node e = new Node("e");
a.connections.add(b);
b.connections.add(a);
b.connections.add(c);
b.connections.add(d);
c.connections.add(b);
c.connections.add(d);
d.connections.add(b);
d.connections.add(c);
d.connections.add(e);
DFS.search(d);
}
}
Nice question.
This is the solution based on the source you posted as comment.
IMPORTANT: There is an error on the start/end table, third row third column should be "end[u] < end[v]" instead of "end[u] > end[v]"
void main(G, s){
for each node v in G{
explored[v]=false
parent[v]=null
start[v]=end[v]=null
}
Global clock = 0
DFS(G, s, s)
}
void DFS(G, s, parent){
explored[s] = true;
parent[s] = parent
start[s]=clock
clock++
for each u=(s,v){
if(explored[v] == false){
DFS(G, v)
}
print (s + "-->" + v +"type: " + getType(s,v))
}
end[s]=clock
clock++
}
String getType(s, v){
if(start[s]<start[v]){
if(end[s]>end[v]) return "Tree edge"
else return "Forward edge"
else{
if(end[s]<end[v]) return "Back edge"
else return "Cross edge"
}
}

Sentinel node in Binary Search Trees

I was wondering if in a way to avoid having to deal with the root as a special case in a Binary Search Tree I could use some sort of sentinel root node?
public void insert(int value) {
if (root == null) {
root = new Node(value);
++size;
} else {
Node node = root;
while (true) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
++size;
return;
} else {
node = node.left;
}
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
++size;
return;
} else {
node = node.right;
}
} else return;
}
}
}
For instance, in the insert() operation I have to treat the root node in a special way. In the delete() operation the same will happen, in fact, it will be way worse.
I've thought a bit regarding the issue but I couldn't come with any good solution. Is it because it is simply not possible or am I missing something?
The null node itself is the sentinel, but instead of using null, you can use an instance of a Node with a special flag (or a special subclass), which is effectively the null node. A Nil node makes sense, as that is actually a valid tree: empty!
And by using recursion you can get rid of the extra checks and new Node littered all over (which is what I presume is really bothering you).
Something like this:
class Node {
private Value v;
private boolean is_nil;
private Node left;
private Node right;
public void insert(Value v) {
if (this.is_nil) {
this.left = new Node(); // Nil node
this.right = new Node(); // Nil node
this.v = v;
this.is_nil = false;
return;
}
if (v > this.v) {
this.right.insert(v);
} else {
this.left.insert(v);
}
}
}
class Tree {
private Node root;
public Tree() {
root = new Node(); // Nil Node.
}
public void insert(Value v) {
root.insert(v);
}
}
If you don't want to use recursion, your while(true) is kind of a code smell.
Say we keep it as null, we can perhaps refactor it as.
public void insert(Value v) {
prev = null;
current = this.root;
boolean left_child = false;
while (current != null) {
prev = current;
if (v > current.v) {
current = current.right;
left_child = false;
} else {
current = current.left;
left_child = true;
}
}
current = new Node(v);
if (prev == null) {
this.root = current;
return;
}
if (left_child) {
prev.left = current;
} else {
prev.right = current;
}
}
The root will always be a special case. The root is the entry point to the binary search tree.
Inserting a sentinel root node means that you will have a root node that is built at the same time as the tree. Furthermore, the sentinel as you mean it will just decrease the balance of the tree (the BST will always be at the right/left of its root node).
The only way that pops in my mind to not manage the root node as a special case during insert/delete is to add empty leaf nodes. In this way you never have an empty tree, but instead a tree with an empty node.
During insert() you just replace the empty leaf node with a non-empty node and two new empty leafs (left and right).
During delete(), as a last step (if such operation is implemented as in here) you just empty the node (it becomes an empty leaf) and trim its existing leafs.
Keep in mind that if you implement it this way you will have more space occupied by empty leaf nodes than by nodes with meaningful data. So, this implementation has sense only if space is not an issue.
The code would look something like this:
public class BST {
private Node root;
public BST(){
root = new Node();
}
public void insert(int elem){
root.insert(elem);
}
public void delete(int elem){
root.delete(elem);
}
}
public class Node{
private static final int EMPTY_VALUE = /* your empty value */;
private int element;
private Node parent;
private Node left;
private Node right;
public Node(){
this(EMPTY_VALUE, null, null, null);
}
public Node(int elem, Node p, Node l, Node r){
element = elem;
parent = p;
left = l;
right = r;
}
public void insert(int elem){
Node thisNode = this;
// this cycle goes on until an empty node is found
while(thisNode.element != EMPTY_VALUE){
// follow the correct path for the insertion here
}
// insert new element here
// thisNode is an empty node at this point
thisNode.element = elem;
thisNode.left = new Node();
thisNode.right = new Node();
thisNode.left.parent = thisNode;
thisNode.right.parent = thisNode;
}
public void delete(int elem){
// manage delete here
}
}

BST to Double-LinkedList Algorithm complexity?

I am looking at the code to do this in CC150. One of its method is as follows, it does this by retrieving the tail of the left sub-tree.
public static BiNode convert(BiNode root) {
if (root == null) {
return null;
}
BiNode part1 = convert(root.node1);
BiNode part2 = convert(root.node2);
if (part1 != null) {
concat(getTail(part1), root);
}
if (part2 != null) {
concat(root, part2);
}
return part1 == null ? root : part1;
}
public static BiNode getTail(BiNode node) {
if (node == null) {
return null;
}
while (node.node2 != null) {
node = node.node2;
}
return node;
}
public static void concat(BiNode x, BiNode y) {
x.node2 = y;
y.node1 = x;
}
public class BiNode {
public BiNode node1;
public BiNode node2;
public int data;
public BiNode(int d) {
data = d;
}
}
What I don't understand is the Time Complexity the author gives in the book O(n^2). What I came up with is T(N) = 2*T(N/2) + O(N/2), O(N/2) is consumed by the getting tail reference because it needs to traverse a list length of O(N/2). So by Master Theorem, it should be O(NlogN). Did I do anything wrong? Thank you!
public static BiNode convert(BiNode root) {//worst case BST everything
if (root == null) { // on left branch (node1)
return null;
}
BiNode part1 = convert(root.node1);//Called n times
BiNode part2 = convert(root.node2);//Single call at beginning
if (part1 != null) {
concat(getTail(part1), root);// O(n) every recursive call
} // for worst case so 1 to n
// SEE BELOW
if (part2 != null) {
concat(root, part2);
}
return part1 == null ? root : part1;
}
public static BiNode getTail(BiNode node) {//O(n)
if (node == null) {
return null;
}
while (node.node2 != null) {
node = node.node2;
}
return node;
}
public static void concat(BiNode x, BiNode y) {//O(1)
x.node2 = y;
y.node1 = x;
}
SAMPLE TREE:
4
/
3
/
2
/
1
As you can see, in the worst case scenario (Big-Oh is not average case), the BST would be structured using only the node1 branch(es). Thus, the recursion would have a have to run getTail() with '1 + 2 + ... + N' problem sizes to complete the conversion.
Which is O(n^2)

Relative complement of two lists where the elements are of different types

I'm looking to remove all elements in a list that can be compared to elements of another list of a different type that don't share a common inheretence, but I do have an equality function for. An example might make it clearer:
given the scaffolding
bool isSomeSortOfEqual(Bottle b, Printer p){
//implementation
}
List<Bottle> bottles = getBottles();
List<Printer> printers = getPrinters();
I would like to do something like this:
List<Bottle> result = bottles.Except(printers, (b, p => isSomeSortOfEqual(b, p));
Are there any builtins for this in .NET, or should I implement this by hand? None of the questions relating to relative complement or except in .NET on stackoverflow seem to deal with having different types.
How about this? The basic idea is to cast the lists to List<object> and then use .Except with an IEqualityComparer<object>
class A
{
public int Ai;
}
class B
{
public int Bi;
}
public class ABComparer : IEqualityComparer<object>
{
public bool Equals(object x, object y)
{
A isA = x as A ?? y as A;
B isB = x as B ?? y as B;
if (isA == null || isB == null)
return false;
return isA.Ai == isB.Bi;
}
public int GetHashCode(object obj)
{
A isA = obj as A;
if (isA != null)
return isA.Ai;
B isB = obj as B;
if (isB != null)
return isB.Bi;
return obj.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
List<object> As = new List<object> { new A { Ai = 1 }, new A { Ai = 2 }, new A { Ai = 3 } };
List<object> Bs = new List<object> { new B { Bi = 1 }, new B { Bi = 1 } };
var except = As.Except(Bs, new ABComparer()).ToArray();
// Will give two As with Ai = 2 and Ai = 3
}
}
not any matches?
from b in bottles
where !printers.Any(p => isSomeSortOfEqual(b, p))
select b;

How to return tree within same level efficiently

I have a tree with nodes that implement this interface
Interface Node {
public boolean hasChildren() {};
}
How can I return a List of List with same treeLevel ?
for example if I have a tree like
1
2 3
4 5 6 7
I'll return a list of list like this {{1}{2,3}{4,5,6,7}}
Thanks.
This is basically a breadth-first traversal, except at each level you keep a list of that level. something like this example C# code:
IEnumerable<Node[]> Traverse(Node root) {
Node[] currentLevel = new [] { root };
Node[] nextLevel = null;
while(true) {
nextLevel = currentLevel.SelectMany(n => n.Children).ToArray();
if (nextLevel.Length > 0) {
yield return nextLevel;
currentLevel = nextLevel;
}
else {
break;
}
}
}

Resources