我正在尝试将一棵通用树(具有一个或多个子级的树)转换为一棵二叉树。我的通用树由 XML 文件名“1.xml”表示,其中包含:
<A>
<B/>
<C>
<E/>
<F/>
</C>
<D/>
</A>
所以我可以像这样表示二叉树:
现在要将此树转换为二叉树,我使用以下方法:
A ---- # -------- # ------ #
| | |
B C--#--# D
| |
E F
(#(DIESE)的数量是指给定节点的兄弟节点的数量) 最右边的节点是树的根。
A <---- # <-------- # <------ #
| | |
B C<--#<--# D
| |
E F
更清楚地说,二叉树就像这张图
为此,我编写了这段代码:
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();
}
}
我得到这个结果(输入 DIESE(父节点的名称)而不是 # ):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<DIESE>
<DIESE>
<DIESE>
<A/>
<B/>
</DIESE>
<DIESE/>
</DIESE>
<D/>
</DIESE>
树缺少节点 C、E、F,所以我不知道为什么? 问题出在递归方法 NaireTreeToBinaryTree
最佳答案
正如您将看到的,复制错误用节点替换了新的子树。
public static Node naireTreeToBinaryTree (Node node,Document d)
{
if (isLeaf(node))
{
//-return node;
return d.createElement(node.getNodeName());
}
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());
Node child2 = naireTreeToBinaryTree(liste.get(i),d);
root.appendChild(child2);
tmp=root;
}
return tmp;
}
}
关于java - 生成二叉树形式N aire Tree-递归方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10957124/