Making a Depth first-search algorithm in java - java

I have the following directed graph implementation
Nodes nod[]
List<Arcs> arc[]
So the node on the n'th position has all his arcs of the list in position n. Of course, the nodes are organized accordingly, so that I can use Binary Search.
Based on this implementation. I wish to create a DFS algorithm. I know very well the pseudo code, adapting to java shouldn't be a problem.
But my question is the following. In DFS we need to start searching from the "top" node. And thinking about it, i dont have this "top" node. Moreover, I have no idea how to get it.
So I ask, how do i get this top node, considering my implementation?
Thanks for the help.

Expanding on my comment:
Assuming that the arcs are directed (i.e., from the parent node to the child only) you can search all of the nodes for the one with no incoming arcs:
// parent_count is an integer array of the same size as nod[]
for i = 1..n
for each arc in arc[i] (arc going from i to j)
increment parent_count[j]
end
end
for k = 1..n
if parent_count[k] == 0
return k
end

DFS/BFS are very common and general algorithms to travel over the graph, both has no special meaning of top node, you could start DFS from any node. For example, DFS is used in topological sort algorithm and it states that we have to start from nodes with no incoming edges.
Could you please highlight what problem you want to solve? This should help us to find nodes that has to be used as a roots for DFS.

Related

Convert General "Family" Tree to Binary Tree (Not BST)

I am currently considering different ways to accomplish the task of converting a family-type general tree (where each parent can have as many children as necessary) to a binary tree such that the left child of the parent node is inserted to the left of the parent and the right child of the parent node is inserted to the right of the (oldest) child node and so on.
This is the structure of how the binary tree must look like when converted from the general tree: https://www.geeksforgeeks.org/convert-a-generic-treen-array-tree-to-binary-tree/
I fed in my data by creating class object GTNode for the General Tree to add the nodes with the following values being passed:
//name = value1; numChildren = value2
GTNode gtn = new GTNode (String name, int numChildren);
No issues with constructor, this is purely to illustrated the main focus of the node is indeed the name of the family member. Thus this really can't be converted and sorted by a Binary Search Tree and is not the point of the resulting program I'm trying to create.
I was able to create methods to traverse the tree just fine, but it really doesn't help in the conversion process to the CONVERTED binary tree.
Therefore I created an additional section of code to create a linked list of the data. The reason why I did this was to establish pointers along the list which would point to the correct parent to add children to. Siblings would then be added to the right of the oldest sibling based on pointers based on where we were along real-time adding of nodes in the tree. By this time you can imagine I have two pointers going in my linked list traversal and three pointers along the tree nodes.
I can't seem to make good progress on an algorithm to create this binary tree from the data. here's a little sample code mostly pseudo code to show you basically how I'm adding nodes to the converted-style binary tree based on general tree data.
p=q=first; //initialize to first node f the linked list of family data
//ex. [Tom, 2] [Marc,1] [Ron,0] [Billy, 0] where Marc and Ron are Tom's children, and Billy is Marc's child)
z=root;
//I already established x, y = root earlier and moved pointer .next in order to add children nodes to the siblings
//here we establish x and y pointers for the tree and add our root node and first child node, which will always be to the left.
//I left it out of the while loop, because I was running into problems with null pointers.
{
while (p.next!=null && q.next!=null)
{
for (i = n; i>0; i--) //int n = node.numChildren; was declared earlier and then decreased
// n-=1 to accommodate the first child being added to left of parent node;
{
//add nodes left or right to parent node: still trying to figure out the appropriate condition
//statements to determine addLeft or addRight from node
}
//here we change the pointer of the GENERAL tree parent node based on the linked list
// add new to binary tree to the right of the last child i.e.
y = new BTNode(p.value,p.numChildren);
y = x.right;
x = y.parent;
x = y; //move pointer along
q = q.next; //q moves from Tom to Marc.
n = q.numChildren;
//go to beginning of while loop and as you can see, if n>0 it iterates based on the number of children
// if n=0 exits loop and creates a new node to the right
}
}
I'm wondering if this is an acceptable track to go down in terms of operability. Optimization I'm not as focused on because this is a difficult task... but could be taken into account.
Looking for pseudocode or java code shippers that would help in establishing an algorithm along these lines, or error in my logic. Again, not looking for an argument against doing a conversion like this because I want to see what it would look like as is.
Thanks!

How do I make a directed unweighted graph with a root node in java?

I am working on a school project and I need to build a Data Structure that has a root node, multiple "ending" nodes(the end of the data Structure), and undefined number of nodes(that have at most two directed links to other nodes) in between the root node and the multiple "ending" nodes. I was thinking of creating some sort of binary graph (represented as a adjacency matrix) where each node can lead to a max of two other nodes, but I don't know how I would construct it in such a way that there is a root node and ending nodes. Can anyone give ideas on how I would do this or a better way to do it? Thank you.(It needs to be in java)
Also, I forgot to mention that I would be adding elements to the data structure and that all paths down the structure would eventually have to lead to one of the preset ending nodes.
Why the adjacency matrix? You're right about the binary tree (or DAG, to be precise). A node can be represented with this class:
class BinaryTree<T> {
BinaryTree<T> left;
BinaryTree<T> right;
}
Ending nodes would be the nodes with left == null && right == null.

Kth Smallest Element in a BST Optimized Solution

I was going through this leetcode problem.
https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
One solution is to do an inorder traversal. Navigate through it and find the kth smallest.
https://www.programcreek.com/2014/07/leetcode-kth-smallest-element-in-a-bst-java/
The other solution I came across is where we pass in a int[]{poss,val} and recursively
However none of this resolve the follow up
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
anyone has any implementation handling this issue. I did see an incomplete example of using custom TreeNode with count but does not fit in since the TreeNode is being passed in.
What changes when implementing lazy deletion into a binary search tree exactly?
Lazy deletion is an option. What this is that you basically have a boolean flag value for each node indicating whether it is deleted or not(but not actually modify structure at all.)

How are nodes in binary search tree stored in java? and other questions related

I am trying to implement a binary search tree. But I do not understand how they would be stored within an array. This is the data structure I am storing it in :
private Comparable[] intHeap;
I am still unsure on how to use comparable, please could someone explain the use of this data structure?
How would I inspect the largest and smallest elements of the binary search tree?
If I had the following tree, would it be stored in the intHeap as 1,3,4,6,7,8,10,13,14?
How do you know which node to go to next, if there is multiple node levels?
Thank you in advance.
Judging from the declaration of an array, what you are building is a binary heap - a specialized tree-based data structure, which is typically stored in an array. Unlike tree structures that rely on explicit references, heaps rely on a clever indexing scheme that "packs" a tree into a linear data structure.
Comparable interface lets you build a heap that can store data of arbitrary classes, as long as they implement Comparable interface. This is useful, because you can build reusable code that works with numbers, strings, or objects of your own type.
How do you know which node to go to next, if there is multiple node levels?
If a node is at the index n, its two children would be at indexes 2n + 1 and 2n + 2. If you are at index k and you want to follow the left subtree, set k = 2*k+1; if you want to follow the right subtree, set k = 2*k+2. Continue following the same algorithm until you hit a null element in your intHeap array.
You need to go through a good tutorial.Just to give you heads up,the node will be like this
Class Node
{
int data;//ideally should be generic.
Node leftChild;
Node rightChild;
...
}
Recommend you to visit Binary Search Tree - Java Implementation

How to get complete subgraph with direction at Nth level starting at Node M in Neo4j

I asked this question How to get subgraph a while back and found while it does give me all nodes and relationships at the Nth level, the answers assume the direction of the relationships either fan out from the starting node or converge to the node. What I am looking for is a complete subgraph that captures all relationships and nodes at a certain level while preserving and relating the direction of the relationships.
For example, if I want all nodes and relationships at depth 2 I can make a directionless query as follows:
START n=node(12345)
MATCH (n)<-[r*1..2]->(m)
RETURN r, m;
This works well as I get all nodes and all relationships, but I find I have no idea what direction the relationships are in.
If I limit the search to a depth of 1 and perform two searches, one incoming and one outgoing, I can get all nodes and relationships with direction that way. I can then recursively do the same query for all nodes found at depth two, discarding any relationships that contain nodes not found beyond the 2nd level from the start. This seems rather painful and manual but it works.
I've also tried using the TraversalDescription framework in the embedded Java API, but that doesn't quite return all relationships. For example, the following snippet gave me all nodes at depth 2, but it missed some relationships between nodes at depth 2:
for ( Path position : graphDb.traversalDescription()
.breadthFirst()
.evaluator( Evaluators.toDepth( 2 ) )
.traverse( templateNode ) )
{
output += position + "\n";
}
Is there an easy way to do this without multiple manual iterations?
Directionless queries are without arrow tips.
If you want to have a direction use:
START n=node(12345)
MATCH (n)-[r*1..2]->(m)
RETURN r, m;
You can access start and endnode of the rel and then output them to infer their direction.
START n=node(12345)
MATCH (n)-[rels*1..2]->(m)
RETURN m, extract(r in relsĀ | [startNode(r),endNode(r),type(r)]);

Categories