【发布时间】:2019-12-18 19:18:19
【问题描述】:
我尝试“线性化”二叉树的每一种可能性,以使其更易于阅读。每种可能性都应添加到以下结构中:
// (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”的所有可能性。
两个基本示例:
Binary end-or tree example (1)
公式: (a | b) & (c | d)
可能性:
{
{a, c}, // or {c, a}, the order doesn't matter
{a, d},
{b, c},
{b, d}
}
Binary end-or tree example (2)
公式: 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', ...
}
非常感谢您的帮助。
【问题讨论】:
-
所以你基本上想将你的公式转换为 DNF(使用树)?
-
这是一个 Java 示例,但用于 CNF。不过,这应该足以让您朝着正确的方向前进。 stackoverflow.com/questions/17238768/…
-
非常感谢您指出 DNF 的问题和另一个主题,我正在研究一种方法(可能不是最有效的)来实现我将在完成后发布的分发。
标签: c# tree binary logical-or logical-and