Im trying to convert a general tree (tree that have one or more children ) to a binary tree .My general tree is represented by an XML file name "1.xml" that contain :
<A>
<B/>
<C>
<E/>
<F/>
</C>
<D/>
</A>
so i can represent the binary tree like this :
Now to convert this tree to an a binary tree i use the following method:
A ---- # -------- # ------ #
| | |
B C--#--# D
| |
E F
(the number of # (DIESE) refer to the number of sibling of a given node ) the right-most node is the root of the tree.
A <---- # <-------- # <------ #
| | |
B C<--#<--# D
| |
E F
more clearly the binary tree is like this picture
to do that i writing this code :
public static Node NaireTreeToBinaryTree (Node node,Document d)
{
if (isLeaf(node))
{
return node;
}
else
{
List<Element> liste = GetChildren(node);
Node tmp= d.createElement(node.getNodeName());
for (int i=0;i<liste.size();i++)
{
Element root = d.createElement("DIESE");
root.appendChild(tmp);
Element child2 = d.createElement(NaireTreeToBinaryTree(liste.get(i),d).getNodeName());
root.appendChild(child2);
tmp=root;
}
return tmp;
}
}
public static void WritingIntoXML (Node node ,Document d)
{
try{
d.appendChild(node);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(d);
// Output to console for testing
StreamResult result2 = new StreamResult(System.out);
transformer.transform(source, result);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
Node root = GetNodeParent("1.xml"); // Get the node parent
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Node a =NaireTreeToBinaryTree (root, doc);
WritingIntoXML (a ,doc);
}
catch (Exception e )
{
e.printStackTrace();
}
}
im getting this result (im puting DIESE(the name of a parent node) instead of # ) :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<DIESE>
<DIESE>
<DIESE>
<A/>
<B/>
</DIESE>
<DIESE/>
</DIESE>
<D/>
</DIESE>
There are tree missing node C,E,F so i don't know why ? is the problem in the recursive methode NaireTreeToBinaryTree