我正在努力解决基于两个非二进制树图的问题,需要将它们一起迭代才能找到有效的组合。
我做了一个有效的基本实现,但它有一些缺陷。我先解释一下。
关键是我有两棵树,每个节点都有“n”个子节点,“n”子节点有另一个“n”,依此类推(“n”是常数,我的意思是“如果” n = 14“然后每个节点有14个孩子,每个孩子还有14个孩子。”
此外,“n”值对于两棵树都是恒定的并且相同。
有了这个概念,我需要找到满足某些条件的两个节点的组合(该条件是用户指定的,所以对于exapmple porpouse,假设我们需要有两个节点具有相同的内容)。
我做了一个遍历所有两棵树的algotihm,但是它以并行模式进行(我的意思是,如果解决方案是root/node1/node2/node5
+ root/node3/node3/node14
它可以工作,但是root/node1/node2
+ root/node14
找不到它。)
所以,我要求一般帮助,而不是一个有效的实现如何制作一个可以解决第二种解决方案的算法,如果你找到一些方法来改进我的代码...将不胜感激。
最后,我在这里留下我的代码,这样你就可以看到问题了(同样,我在java上做了,因为我匆匆忙忙地编写了程序,并且我在java编程更快,例如在C中 - 我说这是因为最终的实现不需要用任何特定的语言编写)
import java.math.BigInteger;
public class TreeAnalyzer{
private String data;
private int pposition;
private int qposition;
private int n;
private boolean found = false;
private BigInteger ten = new BigInteger("10");
public static void main(String[] args){
TreeAnalyzer ta = new TreeAnalyzer();
ta.setPrivateKey(args[0], args[1]);
ta.iterate();
}
public void setPrivateKey(String data, String n){
this.data = data;
this.n = Integer.parseInt(n);
this.pposition = 1;
this.qposition = 1;
}
public void iterate(){
int valid[] = this.getValid(this.getLast());
for(int i = 0;i <= (valid.length / 2);i++){
//restart positions. pposition and qposition represents the depth of each tree.
pposition = 1;
qposition = 1;
iterate(this.getNext(new BigInteger(Integer.toString(valid[i])), pposition), this.getNext(new BigInteger(Integer.toString(valid[++i])), qposition));
}
}
private int getLast(){
//get last part of data
}
private int[] getValid(int num){
//for first node, there are few options that are only valid. With this method we'll find it and save some nodes to be explored
//that options come always in pairs.
}
/*
* The results of comparation can be checked partially as each node have independent parts. Despite that, more than one combination can
* partially match.
*
* When we find a combination of two nodes that match, we increase depth by 1 and start iterating over that point.
*/
private boolean iterate(BigInteger p, BigInteger q){
if(pposition <= 0 || qposition <= 0)
return false;
if(this.found)
return true;
BigInteger p1 = p;
BigInteger q1 = q;
int x = 0;
int y = 0;
for(x = 0;x < n;x++){
for(y = 0;y < n;y++){
if(this.check(p1, q1, pposition, qposition)){
if(this.found){
System.out.println("Result: " + p1 + " and " + q1);
System.exit(1);
}
this.iterate(this.getNext(p1, ++pposition), this.getNext(q1, ++qposition));
p1 = this.getNext(p1, qposition);
}else{
p1 = this.getNext(p1, qposition);
}
}
if(y == 9)
p1 = this.reset(p1, qposition);
q1 = this.getNext(q1, pposition);
}
pposition--;
qposition--;
return false;
}
private BigInteger getNext(BigInteger n, int position){
return n.add(ten.pow(position));
}
private BigInteger reset(BigInteger n, int position){
return getNext(n.mod(ten.pow(position)), position);
}
private boolean check(BigInteger p, BigInteger q, int pposition, int qposition){
//compare some content. It will return true or false, and maybe set "found" flag to true
return false;
}
}