Get all siblings, previous and next in Magnolia/JCR-SQL2 - java

Once you've gotten a node from the JCR, what is the easiest way to get its previous and next siblings?

Not entirely sure if its the easiest way but you may do something like that
Node parent = node.getParent();
NodeIterator siblings = parent.getNodes();
Node firstSibling = siblings.nextNode();
For previous you should do some operations on siblings object but that should be straightforward. This would be the JCR way of doing that.
However, Magnolia has the helper functions which reside under info.magnolia.jcr.util.NodeUtil package
Then One may use the following;
NodeUtil#getSiblingBefore()
NodeUtil#getSiblingAfter()

Related

Java; go back up a file tree until a specific folder

I want to recursively go backwards up a directory until I find a specific parent folder.
Basically what I'm after is
while (!child.getParentFile().equals(greatGrandparent)) {
// keep going backwards until it does
}
Where child could be 10, 20, 50 levels underneath greatGrandparent
All I can find online is saying to start and grandparent and check each child until I find the child I'm looking for, but there could be a million children under the grandparent and I don't want to check them all when I know I just need to go back up the tree, if that makes sense.
Is there a standard pattern for this?
What's wrong with
while (!child.getParentFile().equals(greatGrandparent)) {
child = child.getParentFile();
}
Sounds like you are looking for simply this:
while (!child.getParentFile().equals(greatGrandparent)) {
child = child.getParentFile();
}
If this is not what you are looking for, you'll need to explain your problem better.

How to create a simple unordered tree(not BST) in java with given node pairs(u,v)?

Problem is I don't understand how to create a tree. I have gone through many code examples on trees but I don't even know how to work with/handle a node and hence I don't understand how the node class works(that was present in all the program examples ). When i try to use methods such as appendChild(as mentioned in java docs),I get an error,and I am asked to create one such appendChild method inside that node class within the main program. Couldn't understand why that happened.
I am given integer pairs((u,v) meaning there is an edge between u & v) of nodes and I also need to know if any Element-to-node conversion is required for using u and v(of type integer) as nodes.
Please bear with me since my basics are weak. Little explanation on how the entire thing works/functions would be very helpful.
Thank you.
EDIT 1: I went through the following links:(hardly found anything on just unordered trees) http://www.cs.cmu.edu/~adamchik/15-121/lectures/Trees/code/BST.java http://www.newthinktank.com/2013/03/binary-tree-in-java/ . Tried to modify these codes to meet my own purpose but failed.
I only got a blurry idea and that is not enough for implementation. I am trying to make a simple unordered tree,for which i am given u v pairs like:
(4,5) (5,7) (5,6). I just need to join (4<--5),(5<--7) and (5<--6). So how do I write a node class that only joins one node to the prev node? Besides,to do only this,do I need to bother myself with leftchild,rightchild? If not,how will I be able to traverse the tree and do similar operations such as height diameter calculation etc later?
Thank you for your patience.
Well Its not entirely clear whether you want an explanation on tree creation in general, on some tree implementation you have found, or you have a basic code already that you cannot get working. You might want to clarify that :).
Also tree creation in general:
Most explanation and implementation you will find might be "overly" elegant :). So try to imagine a simple linked list first. In that list you have nodes(the elements of the list). A node contains some valuable data and a reference to an other node object. A very simple tree is different only in that a node have more than one reference to other nodes. For example it has a Set of references, its "children".
Here is a VERY crude code only as an example for addChild() or appendChild in your case:
public class Node {
private String valueableData;
private Set<Node> children;
public Node(){
this.children=new HashSet<Node>();
}
public Node (String valueableData){
this.valueableData=valueableData;
this.children=new HashSet<Node>();
}
public void addChild(Node node){
children.add(node);
}
}
Now this implementation would be quite horrible (I even deleted the setter/getters), also it would be wise to keep the root nodes reference in some cases, and so on. But you might get the basic idea.
You might wanna create a cycle or recursion to go over the (u,v) integer pairs. You create the root node first then you just addChild() all the other nodes recursively, or create every node first then setChild() them according to your rules.

How to get descendants up to a certain level in a Tree?

Which Tree data structure in Java allows querying for different levels of children? I have looked at TreeNode, JTree. But they dont seem to support multi level querying.
Given a Tree, for a specific node, I want to get the descendants up to a certain level n. Is there an existing implementation that I can use or should I write my own?
Thanks!
It's not that hard to write a breadth-first traversal and visit all the children up to a specified level. Here is some pseudocode. Assume you have a new class:
public class NodeWithLevel {
Node node;
int level;
}
This class is only a wrapper used for this algorithm.
Then the "get all nodes up to level N" method would be:
Queue<NodeWithLevel> queue;
queue.enqueue(<0, tree.root>);
currentLevel = 0;
while(currentLevel < N) {
NodeWithLevel current = queue.dequeue();
currentLevel = current.level;
// do whatever with current
for(Node child: current.node.children) {
queue.enqueue(<current.level + 1, child>);
}
}
DefaultMutableTreeNode supports several traversals, using any one of them to reach your goal is left (no pun intended, it's by the api :) to the user.
If you're not afraid of a complex API, the DOM might be what you need. You can query it through XPath, apply events to its nodes, etc...
The only thing that springs to mind is swing's DefaultTreeModel but that would still require a bit of coding on your side for the logic to get children up to a certain level.
It shouldn't be too hard to roll your own implementation.

Red-black tree - How to find the node's parent?

In red-black tree, when rotate, you need to know who is the parent of particular node.
However, the node only has reference to either right or left child.
I was thinking to give a node instance variable "parent" but just for this reason I don't think it is worth doing so and also it would be too complicated to change parent reference per rotation.
public class Node {
private left;
private right;
private isRed;
private parent; //I don't think this is good idea
}
So, my solution is to write findParent() method that use search to find parent. I am wondering if there is any other way to find a node's parent?
My solution:
sample tree:
50
/ \
25 75
If you want to find parent of Node 25, you pass something like:
Node parent = findParent(Node25.value);
and it returns node50.
protected Node findParent(int val) {
if(root == null) {
return null;
}
Node current = root;
Node parent = current;
while(true) {
if(current.val == val) { //found
return parent;
}
if(current == null) { //not found
return null;
}
parent = current;
if(current.val > val) { //go left
current = current.left;
}
else { //go right
current = current.right;
}
}
}
The use of a parent pointer is optional. If you forgo the parent pointer then you will have to write insert/delete operations using recursion (the recursive method calls preserve the parent information on the stack) or write an iterative version which maintains its own stack of parents as it moves down the tree.
A very good description of red-black trees can be found here
http://adtinfo.org/
That includes descriptions of a number of rbtree implementations including with and without parent pointers.
If you do want to save on space (and that is fair enough) a really excellent description of an rbtree implementation can be found here
http://www.eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx
The method you have described for searching for a node's parent would be very inefficient if used by the insert/delete implementations. Use a pointer or use recursion.
I was thinking to give a node instance variable "parent" but just for this reason I don't think it is worth doing so
Having your nodes have a parent reference requires one extra pointer/reference per node. Compare this with needing to traverse the tree whenever you need to know the parent for a given node.
This is then a trade-off between
The cost of maintaining an extra reference, and keeping it up to date whenever you modify a node.
The computational cost and complexity of having to traverse the tree to find a parent of a given node
I think that the choice between these two options is somewhat subjective but personally I would choose to simply keep track of the parent references.
As a point of reference for you, java.util.TreeMap is implemented as a Red-Black tree which Entry nodes that contain left, right, and parent references.
As you traverse the tree to get to your pivot node you can cache the previous parent or if you need more than one level of "undo" you could cache each traversed node on to a stack.
This cache would be a variable local to your rotation algorithm so it wouldn't require any more space in the tree or expensive additional traversals.
It's definitely better to store the parent than to look it up. Updating parent reference is not that complex.
Another solution, besides parent pointers and querying the parent all over again is to maintain an ancestor stack.
Suppose someone wishes to insert 23 into the following tree:
Red Black Tree
Generally the algorithm to insert is:
Find node where 23 would be if it is in the tree
If 23 is already there, return failure
If 23 is not already there, put it there.
Run your re-balancing/coloring routine as needed.
Now, to use the stack approach, you allocate a stack big enough to support one node per level of your tree (I think 2 * Ceiling(Log2(count)) + 2) should have you covered. You could even keep a stack allocated for insertion or deletion and just clear it whenever you start an insertion.
So -- Look at the root. Push it onto the stack. 23 is greater than value in the root, so go right. Now push node current node (value 21) onto the stack. If 23 is in the tree, it must be to the right of current node. But the node to the right of the current node is a null-sentinel. Thus, that null-sentinel should be replaced with a node with your value. The parent is the item on the top of the stack (most recently pushed), the grandparent is next in line ... etc. Since you seem to be learning ... Java supplies a stack interface for you so you won't need to develop your own stack to do this. Just use theirs.
As to whether this is better than the parent pointer approach, that seems debatable to me -- I would lean to the parent pointer approach for simplicity and elimination of the need to maintain an ancillary data structure or use recursion extensively. That said, either approach is better than querying the parent of the current node as you apply your re-balancing/coloring routine.

Efficient way to walk through an object tree?

I've got a set of TreeNodes, each of which has an id, a Collection of parent nodes, and a collection of child nodes.
For a given node Id, I'm looking for an efficient way to generate all the links that pass through that node. So in short, start at the node, and iterate through all its children. If a node has more than one child, create a link for each child. The traverse the children etc..
I'd also like to be able to do this in an 'upward' direction, through the parent nodes.
Is there a simple algorithm to do this?
EDIT: Oh, and I'd like to be able to output the id's of all the nodes in a given chain...
You are looking for a Breadth First or Depth First Search. At first it is not more than the following (this is depth first search).
Visit(Node node)
{
foreach (Node childNode in node.Children)
{
Visit(childNode);
}
DoStuff(node);
}
The problem is that the graph may contain cycles, hence the algorithm will enter infinite loops. To get around this you must remember visited nodes by flaging them or storing them in a collection. If the graph has no cycles - for example if it is a tree - this short algorithm will already work.
And by the way, if a TreeNode has multiple parents, it's not a tree but a graph node.
Well, if the nodes have a reference to the parent, it's simple as getting the parent recursively (once in a tree, each node has only one (or none at all, if it is a root) parent.
If there's no such reference, than you could use a breadth-first search, for instance, having as initial set your collection of parent nodes.
-- EDIT --
Once a node may have more than one parent, then you're dealing with a graph. There are also graph traversal algorithms (see table at the side).
Make sure that, if your graph has a cycle, you won't end up having a infinite loop
You might want to check out depthFirstEnumeration() and breadthFirstEnumeration() on DefaultMutableTreeNode. However, this doesn't solve your problem of wanting to navigate the tree in a bottom-up fashion.

Categories