reconstructing a tree from its preorder and postorder lists

前端 未结 7 1877
既然无缘
既然无缘 2020-11-28 04:26

Consider the situation where you have two lists of nodes of which all you know is that one is a representation of a preorder traversal of some tree and the other a represent

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 05:00

    Consider an arbitrary tree T as the quadruple (A, B, C, D), where A is the root node, B is the root node of the first child, C is a vector of any non-empty children of B, and D is a vector of any non-empty siblings of B. The elements of C and D are themselves trees.

    Any of A, B, C and D may be empty. If B is empty, so must be C and D; if A, then everything.

    Since nodes are unique, the sets of nodes contained anywhere within C and D are disjoint, and neither contains A or B.

    Functions pre() and post() generate ordered sequences of the form:

    pre(T) = [A, B, pre(C), pre(D)]

    post(T) = [post(C), B, post(D), A]

    where the function applied to a vector is defined to be the concatenation of the sequences resulting from applying the function to each element in turn.

    Now consider the cases:

    • if A is empty, the output of both functions is the empty sequence []
    • if B is empty, the output of both functions is just [A]
    • if C and D are empty, pre(T) = [A, B] and post(T) = [B, A]
    • if just C is empty, pre(T) = [A, B, D'] and post(T) = [B, D'', A] (where the primes indicate some permutation of the nodes contained within D)
    • if just D is empty, pre(T) = [A, B, C'] and post(T) = [C'', B, A]
    • if none are empty, pre(T) = [A, B, C', D'] and post(T) = [C'', B, D'', A]

    In all cases we can unambiguously partition the members of the two output sequences into the appropriate subsequences, by using A and B (if present) as delimiters.

    The question then is, can we also partition the vector sequences? If we can, then each can be recursively processed and we're done.

    Since the result of pre() will always be a chain of sequences starting with A nodes, and the result of post() will always be a chain of sequences ending with A nodes, we can indeed divide them up, provided that the A nodes are never empty.

    This is where the process falls down in the case of binary (or indeed any) trees with fixed children that may independently be empty. In our case, however, we have defined C and D to contain only non-empty nodes, and so the reconstruction is guaranteed to work.

    Um, I think so, anyway. Obviously this is just an argument, not a formal proof!

提交回复
热议问题