好的,这有点棘手。
我有一堆代码采用表达式树,例如:
((a + b)/(c + d) + sqrt(e))
以前缀形式存储在向量中(我使用的是 C++,但我只需要算法):
+(/(+(a,b),+(c,d)),sqrt(e))
//括号只是为了帮助您阅读它。每个运算符和终端都是向量中的一个元素。
现在有另一种表示表达式树的方法,称为 ORF 形式
(论文第三页:http: //arxiv.org/ftp/cs/papers/0102/0102027.pdf)
在这种形式中,您可以将树表示为从左到右、从上到下阅读树。
((a + b)/(c + d) + sqrt(e))
现在变成:
+/sqrt++eabcd
我一直未能做的是创建一个可以转换的算法:
+/sqrt++eabcd
//ORF 成:
+(/(+(a,b),+(c,d)),sqrt(e))
//前缀
到目前为止,我所拥有的只是一些代码来获取不同级别的树的广度:
bool ConvertPrefixToORF(const std::vector<Node> & individual,
std::vector<Node> & ETindividual){
bool all_terminal = false;
int breadth;
int breadthOfDepth[individual.size()];
int depthCounter = 0;
breadthOfDepth[0] = 1;
//Resize only once.
ETindividual.reserve(individual.size());
while (all_terminal == false) {
//Reset breadth
breadth = 0;
//Iterate over next level and calculate depth of level after that.
for (int i = 0; i < breadthOfDepth[depthCounter]; i++) {
all_terminal = true;
//If the individual is a function...
if (individual[current+i].isFunction()) {
//Get individual from i'th item at this depth
function f = individual[current + i];
//Increment breadth of next level with arity
breadth += f->getArity();
//if a single function is found
all_terminal = false;
}
}
//Go down a level in the tree.
depthCounter++;
//Set the breadth of that tree depth:
breadthOfDepth[depthCounter] = breadth;
}
}
提前感谢您的帮助!这让我很头疼。哦,这对性能至关重要:(