【发布时间】:2014-10-09 08:04:47
【问题描述】:
我有简单的代码,可以打印树中特定节点的路径。我使用 java String 的实现如下
//using strings
public static void getPathS(Node node,String path,int key){
if (node == null) {
return;
} else if(node.data == key) {
System.out.println(path+" "+key);;
}
getPathS(node.left,path+" "+node.data,key);
getPathS(node.right,path+" "+node.data,key);
}
假设有如下给出的树,
如果我在 3 上调用 getPathS,上面的实现会打印出来
1 34 3 //path from root to the element
如果我使用下面的 ArrayList 实现相同的方法
public static List getPath(Node node, List<Integer> path, int key) {
if (node == null) {
//1 . path = new ArrayList<Integer>();
path = new ArrayList<Integer>();
// 2. or tried path.clear() -- it should clear the path
//return path;
return null;
} else if (node.data == key) {
path.add(node.data);
return path;
}
path.add(node.data);
return nonNull(getPath(node.left, path, key), getPath(node.right, path, key));
}
private List nonNull(List path1, List path2) {
if (path1 != null)
return path1;
if(path2 !=null )
return path2;
return null;
}
// class Node { Node left, Node right , int data; };
//Code to call getPath
Node node = new Node(1);
node.left = new Node(2);
node.left.left = new Node(4);
node.right = new Node(34);
node.right.right = new Node(3);
System.out.println(getPath(node, new ArrayList(), 3));
在第二个实现中,我尝试了两种方法,当我们得到 NULL 节点时,在第一种方法中,如果我将新的 ArrayList 分配给路径,它会打印所有元素,即
[1, 2, 4, 34, 3]
如果我使用path.clear(),它只会打印最后一个元素,即要搜索的元素。
我们如何确保ArrayList 在递归中作为字符串工作?
【问题讨论】:
-
nonNull(arg1,arg2)是什么? -
请检查更新的代码
-
好的,谢谢。请第一时间贴出调用
getPath()的代码。这里的问题是你正在向我猜的同一个列表中添加/删除元素。您需要使用某种回溯。几分钟后我会想出一些办法。 -
仅供参考,您的新
nonNull()方法的作用完全相同;-)
标签: java algorithm data-structures arraylist