Order of recursive tree index? - java

I have tree where all leafs have index, when tree is rescursively lodaded form database, database will order tree by indexes. First it gets root nodes sorted by index and so on. Now I need to implement action how user can sort these indexes by pressing up/down arrow icons. When user presses down then index should take index that is under it's own index and when up arrow is pressed it should do vice versa. I just don't know what would be best way to implement this kind of functionality.

Since your question is a bit vague, this answer assumes you know what you are doing when it comes to the database stuff (I would reccommend hibernate for java if not) and the following code is meant to give you some ideas for implementing your solution.
//If I have understood your question, you want two nodes to swap position in the tree structure
public static swapNode(Node parent, Node child)
{
Long superId = parent.getParentId();
child.parentId(superId);
parent.setParentId(child.getId());
child.setId(parentId);
//update children lists of parent and child
//update parent ids of children lists
//save changes to database
}
//create tree structure from database. Assumes nodes have been loaded from a database
//table where each row represents a node with a parent id column the root node which has parent id null)
//invoke this with all nodes and null for parentId argument
public static List<Node> createNodeTree(List<Node> allNodes, Long parentId)
{
List<Node> treeList = new ArrayList<Node>();
for(Node node : nodes)
{
if(parentIdMatches(node, parentId))
{
node.setChildren(createNodeTree(allNodes, node.getId()));
treeList.add(node);
}
}
return treeList;
}
private static boolean parentIdMatches(Node node, Long parentId)
{
return (parentId != null && parentId.equals(node.getParentId()))
|| (parentId == null && node.getParentId() == null);
}
//The objects loaded from the database should implement this interface
public interface Node
{
void setParentId(Long id);
Long getParentId();
Long getId();
List<Node> getChildren();
void setChildren(List<Node> nodes);
}

Related

Recursively delete all sublists in a list

I have a Node class. It has a children ArrayList. That list consists of Nodes as well. And said nodes have children lists, and so on.
Basically, it's a tree in somewhat not so convenient form. Let's say I want to delete someNode from it. So how to clear all of the child lists recursively?
I have a hasChildren() method, which returns if specified node has children, I think it has to help me, but can't figure out how yet. I've also got getChildren() method which returns list of children.
Here's some of my code, but it is wrong all over the place.
public void removeChild()
{
while(hasChildren())
{
getChildren();
removeChild();
}
children.clear();
}
You can implement a Queue which you can use to put every Node's children and then pop from it to remove them.
Something like this.
Queue<Node> queue = new LinkedList<>();
queue.add(node); //node to remove
while(!queue.isEmpty()) {
Node currentNode = queue.pop();
for(Node n : currentNode.getChildren) {
queue.add(n);
{
currentNode.getChildren.clear();
}
UPDATE: To do it recursively you could implement something like this (just be aware of stack size in java).
public void removeChildren(Node node)
{
for(Node n : node.getChildren()) {
removeChildren(n);
}
node.getChildren().clear();
}
In my opinion you just need to clear the children (as shown below) and the Garbage collector will automatically free rest of the objects.
public void removeChild()
{
if(hasChildren())
{
children.clear();
}
}

Depth first search in java - how to go back to parent node?

I'm trying to do a depth first search in Java recursively. At the moment, the code runs through my graph fine, but it never backtracks to find a route when they're are no more nodes to visit. I'm having a bit of a mental block honestly. What would be the best way to go back to the parent node?
Here is my code so far:
private final Map<Character, Node> mNodes;
private final List<Edge> mEdges;
public DepthFirstSearch(Graph graph){
mNodes = graph.getNodes();
mEdges = new ArrayList<>(graph.getEdges());
for(Node node : mNodes.values()){
node.setVisited(false);
}
}
public void depthFirstSearch(Node source){
source.setVisited(true);
List<Node> neighbours = source.getNeighbours(mEdges);
for(Node node : neighbours){
if(!node.isVisited()){
System.out.println(node.getName());
depthFirstSearch(node);
}
}
}
And the getNeighbour code:
public List<Node> getNeighbours(List<Edge> edges) {
List<Node> neighbours = new ArrayList<>();
for(Edge edge : edges){
if(edge.getFrom().equals(this)){
neighbours.add(edge.getTo());
}
}
return neighbours;
}
Added code for trying Jager's idea:
public void depthFirstSearch(Node source){
source.setVisited(true);
List<Edge> neighbours = source.getNeighbouringEdges(mEdges);
for(Edge edge : neighbours){
if(!edge.getTo().isVisited()){
System.out.println(edge.getTo().getName());
depthFirstSearch(edge.getTo());
}else{
depthFirstSearch(edge.getFrom());
}
}
}
Well, typically you have a root node that has children. Each child can have children of its own. So you would rather do:
public void depthFirstSearch(Node source)
{
for(Node node : source.getChildren())
{
System.out.println(node.getName());
depthFirstSearch(node);
// and right here you get your back tracking implicitly:
System.out.println("back at " + node.getName());
}
}
Note that I do not have a necessity for a member visited...
Edit:
Now that you provided your data structure, let me propose another approach:
class Node
{
// all that you have so far...
private char mId;
private List<Node> mChildren = new ArrayList<Node>();
public char getId()
{
return mId;
}
public List<Node> getChildren()
{
return Collections.unmodifiableList(children);
}
// appropriate methods to add new children
}
The id replaces the key of your map. Then you simply have a root Node mRoot to start with somewhere. This is the typical way to implement trees.
You might want to go up from a child node directly. Then you'd additionally need a private Node parent; in the node class (immediately being set to this when adding a child to the private list and set to null, when being removed). You won't use this for backtracking, though, so the depth first search above remains unchanged.
Guessing: you are "getting" the neighbors for mEdges which seems to be a field of the surrounding class.
Most likely, you should ask each node for its own edges upon visiting it.

Iterators over Tries in Java

I am currently trying to implement a trie data structure for integer tuples. And have implemented as follows:
import java.util.ArrayList;
public class TrieNode {
int num;
ArrayList<TrieNode> links;
boolean endOfTuple;
public TrieNode(int num)
{
this.num = num;
links = new ArrayList<TrieNode>();
this.endOfTuple = false;
}
}
I then have a trie class as follows:
public class Trie {
TrieNode root;
public Trie() {
root = new TrieNode(-1);
}
public void insertTuple(int[] tuple)
{
int l = tuple.length;
TrieNode curNode = root;
for (int i = 0; i < l; i++)
{
TrieNode node = new TrieNode(tuple[i]);
if(!curNode.links.contains(node)){
curNode.links.add(node);
}
curNode = curNode.links.get(curNode.links.indexOf(node));
}
curNode.endOfTuple = true;
}
}
I can add values to this trie, but i need to be able to iterate over this and was wondering how i could do this? For example if i wanted to print the tree using an iterator...Any help will be great...
All you need for an interator is to implement the Iterator interface, which only requires that you supply boolean hasNext() and Integer next(). So the question to ask is: how do represent a position in your trie, such that it's possible to (a) fetch the value associated with that position, and (b) figure out the "next" position given a current one?
I'll refrain from posting an actual solution since I'm not sure whether this is homework. But consider: you can represent a "current position" in your trie just by choosing a particular trie node, and the path of trie nodes you used to reach it. Then you can compute the "next" element recursively: if the current element is a node that has children, then find the first child for which endOfTuple is true. If the current element doesn't have children, then go to its parent and advance to that parent's next child. If that parent doesn't have next children, then go it its parent's next child, etc.

How do I loop through an array in Java?

Related to my question about how to build a tree-like structure, the data I receive from the server are in arrays like this: {School Chair Table Chalk}
How can I loop through this so that:
School becomes parent of Chair
Chair becomes parent of Table
Table becomes parent of Chalk
Assuming a Node class that offers a constructor which accepts the node's value as an argument and method addChild that adds another Node as a child and sets itself as the child's parent, the code could look like this:
Node currentNode = null;
for(String value: array) {
Node node = new Node(value);
if(currentNode != null) {
currentNode.addChild(node);
}
currentNode = node;
}
Are they always in a list that becomes hierarchical in order? I would suggest creating a simple wrapper class...pardon my syntax, as I've been playing in C# for a while now:
public class Node {
public string description;
public Node child;
public Node(List<string> descriptions) {
this.description = descriptions.RemoveAt(0);
if (descriptions.Count > 0) {
this.child = new Node(descriptions); //create child node with remaining items
}
}
}
This will take issue if you pass in a list w/ zero items to the constructor, but that's easily remedied.

Using recursively returned reference to node in tree does not allow changes to the node itself

My data structures class is working with trees. We are implementing a 3-ary tree, containing 2 values with a reference to a left, middle, and right node (left subtree is less than value 1, middle subtree is between value 1 and value 2, right subtree is greater than value 2). An interface has been provided for the Tree class, and the find, insert, and delete methods must be recursive. The client code which this will be tested against uses the insert method repeatedly to create the tree, and the root starts off as null.
I'm trying to insert values into the tree recursively by finding the parent node in a separate private method, then changing the returned node as appropriate. The problem currently is that the method returns the initial node, which is the root, and correctly creates a new node with the value because the root is null. However, the root remains null.
I'm pretty certain this is due to the way that references and values work in Java (similar to C# as described in this article by Jon Skeet); given the constraints, how should I change this to allow insertions into the tree? Below is the current insert method in the tree class, along with the similar private method.
public void insert(AnyType newData)
{
// If insert node is null, make a new node with newData as first key
TernaryNode<AnyType> insert_node = findNode(newData, root);
if (insert_node == null)
{
insert_node = new TernaryNode<AnyType>(newData);
}
else
{
// Get the key that is equal if the insert node is not null
if (insert_node.getKey1() == null)
{
insert_node.setKey1(newData);
}
else
{
insert_node.setKey2(newData);
}
}// end else
}// end insert
private TernaryNode<AnyType> findNode(AnyType item, TernaryNode<AnyType> node)
{
TernaryNode<AnyType> current_node = node;
if (current_node != null)
{
if (current_node.getKey1() != item &&
current_node.getKey2() != item)
{
// Comparator checks left
if (compare.compare(current_node.getKey1(), item) <= -1)
{
return findNode(item, current_node.left);
} // Comparator checks right
else if (compare.compare(current_node.getKey2(), item) >= 1)
{
return findNode(item, current_node.right);
}// Comparator checks middle
else
{
return findNode(item, current_node.middle);
}
}// end while
}// end if
// Return current node even if it is null
return current_node;
}// end findNode
Unless you're assigning something to the root member, it will never acquire a value. You probably need some sort of outer container for your tree, similarly to how an XML document (which is also a tree) has an outer Document object which is distinct from the actual document root node.
TernaryNode<AnyType> insert_node = findNode(newData, root);
if (insert_node == null)
{
insert_node = new TernaryNode<AnyType>(newData);
root = insert_node;
}

Categories

Resources