简体   繁体   English

确定树木的走行是否先行广度,深度优先或不行

[英]Determining if a tree walk is breadth first, depth first, or neither

Given a tree T and a sequence of nodes S, with the only constraint on S being that it's done through some type of recursion - that is, a node can only appear in S if all of its ancestors have already appeared, what's a good algorithm to determine if S is a breadth first visit, a depth first visit, or neither? 给定一棵树T和一个节点S的序列,对S的唯一约束是它是通过某种类型的递归完成的-也就是说,如果一个节点的所有祖先都已经出现,则该节点只能出现在S中。确定S是广度优先访问,深度优先访问还是两者都不是?

A brute force approach is to compute every breadth first and depth first sequences and see if any is identical to S. Is there a better approach? 蛮力方法是计算每个广度优先和深度优先序列,看看是否与S相同。是否有更好的方法?

What if we don't want a yes or no answer, but a measure of distance? 如果我们不希望回答是或否,而是要衡量距离,该怎么办?


UPDATE 1 By measure of distance, I mean that a visit may not be an exact BFS, but it's close (a few edits might make it one); UPDATE 1通过距离的度量,我的意思是一次访问可能不是一个确切的BFS,但是它是接近的(一些编辑可以使之成为一个)。 I'd like to be able to order them and say BFS < S < R < U < DFS. 我希望能够订购它们并说BFS <S <R <U <DFS。

UPDATE 2 Of course, a brute force enumeration of every BFS or DFS can answer the question; 更新2当然,每个BFS或DFS的强力枚举都可以回答这个问题。 I'd like something more efficient. 我想要更高效的东西。

You have the tree and the sequence, right? 你有树和序列,对不对? In that case it is pretty easy to determine if a sequence is breadth first search or not, and if it is depth first or not. 在那种情况下,很容易确定一个序列是否是广度优先搜索,以及它是否是深度优先。

To check if it is breadth first: divide the nodes into groups L0, L1, ..., Lk where L0 is the set of 0 level nodes (there is only one root node, so its size is 1), L2 is the set of level 1 nodes and so on. 要首先检查其广度:将节点分为组L0,L1,...,Lk,其中L0是0个级别节点的集合(只有一个根节点,因此其大小为1),L2是集合1级节点的数量等等。 If sequence S = (permutation(L0), permutation(1), ...) then it is a breadth first search. 如果序列S =(permutation(L0),permutation(1),...),则为广度优先搜索。

To check if it is depth first: start with a pointer to the first node in the sequence and root node of the tree. 要检查深度是否首先:从指针开始,指向树的序列和根节点中的第一个节点。 They should be same. 它们应该是相同的。 Next element of the sequence must be a child of previous node, if the previous node has any children at all. 如果前一个节点根本没有任何子节点,则序列的下一个元素必须是前一个节点的子节点。 If there is a conflict then it is not a DFS sequence. 如果存在冲突,则不是DFS序列。 If there is no child, then the next sequence element must be child of parent of previous node,... and so on. 如果没有子节点,则下一个序列元素必须是上一个节点的父节点的子节点,等等。 This approach is not as complicated as it sounds and could be easily implemented with the help of a stack. 这种方法听起来并不复杂,并且可以借助堆栈轻松实现。

I am not very sure for your need for "measure of distance". 我不太确定您是否需要“距离测量”。 But as you can see, both of these approaches can return number of conflicts. 但是如您所见,这两种方法都可以返回大量冲突。 Maybe you can use it to calculate "distance"? 也许您可以用它来计算“距离”?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM