Java 递归方法最大深度-静态变量
我想使用递归方法获得XML文件的最大深度,首先我声明了变量Java 递归方法最大深度-静态变量,java,xml,algorithm,recurrence,Java,Xml,Algorithm,Recurrence,我想使用递归方法获得XML文件的最大深度,首先我声明了变量 public static int maxdepth=0; private static void GetDepth(NodeList nl, int level,int maxdepth) { level++; if (maxdepth<level) { maxdepth= level; } if(nl != null && nl.getLengt
public static int maxdepth=0;
private static void GetDepth(NodeList nl, int level,int maxdepth) {
level++;
if (maxdepth<level)
{
maxdepth= level;
}
if(nl != null && nl.getLength() > 0){
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element)
{
GetDepth(n.getChildNodes(), level, maxdepth);
}
}
}
}
public static void main(String[] args) {
NodeList nl = root.getChildNodes();
GetDepth(nl,level,maxdepth);
System.out.println(maxdepth);
}
公共静态int maxdepth=0;
私有静态void GetDepth(nodelistnl,int-level,int-maxdepth){
级别++;
if(最大深度0){
对于(int i=0;i
当我显示变量maxdepth的值时,我收到值0,因为
getDepth
的方法签名中的声明int-maxdepth
隐藏了静态变量maxdepth
。将其从签名中删除:
private static void GetDepth(NodeList nl,int level)
然后该方法将起作用。在此代码部分:
if (maxdepth<level)
{
maxdepth= level;
}
if(maxdepth您可以使用XPath 2.0作为一行程序来完成:
max(for $n in //* return count($n/ancestor::*))
即使在Java中,您也会使其变得比实际情况困难得多:
public int maxDepth(Node node) {
int max = 0;
NodeList kids = node.getChildNodes();
if (kids.getLength() == 0) {
return 0;
}
for (int i=0; i<kids.getLength(); i++) {
int kidMax = maxDepth(kids.item(i);
if (kidMax > max) max = kidMax;
}
return max + 1;
}
public int maxDepth(节点){
int max=0;
NodeList kids=node.getChildNodes();
if(kids.getLength()==0){
返回0;
}
对于(int i=0;i max)max=kidMax;
}
返回最大值+1;
}
未测试。您有两个变量都名为maxdepth,因此在您的第一个方法中,当您说maxdepth=level时,您只影响在您的方法参数中声明的变量,而不影响您在类中声明的实际字段。另一方面,与执行level++不同,这是在递归过程中增加level的一种更常见的做法函数在递归调用时为传递级别+1:GetDepth(n.getChildNodes(),级别+1)