我尝试“线性化”二叉树的每一种可能性,以使其更易于阅读。每种可能性都应添加到以下结构中:
// (x1 AND x2) OR (x2 AND x3)
List<List<Node>> possibilities = new List<List<Node>>() {
{ x1, x2 },
{ x2, x3 }
};
从树形结构生成基于列表的可能性时,我遇到了一些困难。在许多情况下不返回正确答案的简化版本或我的算法是:
class TreeDecomposer {
public List<TreePath> Possibilities = new List<TreePath>();
// TreePath = { List<TreeNode> path, bool IsAdded }
public TreeDecomposer(AbstractTree tree) {
DecomposeTree(tree, new TreePath());
}
public void DecomposeTree(AbstractTree tree, TreePath path)
{
// Add the path to the list of possibilities
if (!path.IsAdded)
{
Possibilities.Add(path);
path.IsAdded = true;
}
// Recursive browse
if (tree is TreeConnector) {
TreeConnector treeConnector = (TreeConnector)tree;
if (treeConnector.Connection == "&")
{
DecomposeTree(treeConnector.LeftTree, path);
DecomposeTree(treeConnector.RightTree, path);
}
else if (treeConnector.Connection == "|")
{
TreePath clonedPath = (TreePath)path.Clone(); // deep clone
DecomposeTree(treeConnector.LeftTree, path);
DecomposeTree(treeConnector.RightTree, clonedPath); // somehow 'or' operator multiplies possibilities by two?
}
}
// Leaf
else if (tree is TreeValue) {
TreeValue treeValue = (TreeValue)tree;
path.Add(treeValue);
}
}
}
我需要帮助来找到与我的树结构一起使用的正确算法来浏览树并构造“AND-path”的每个可能性。
两个基本示例:
公式: (a | b) & (c | d)
可能性:
{
{a, c}, // or {c, a}, the order doesn't matter
{a, d},
{b, c},
{b, d}
}
公式: a & ((b | c) & d)
可能性:
{
{a, b, d}, // or {d, b, a}, the order doesn't matter
{a, c, d}
}
树结构:
实现或树结构如下:
abstract class AbstractTree {}
class TreeConnector: AbstractTree
{
public string Connection; // '&' or '|'
public AbstractTree LeftTree;
public AbstractTree RightTree;
}
class TreeValue : AbstractTree
{
public string Data; // 'a', or 'b', ...
}
非常感谢你的帮助。