Find whether a tree is a subtree of other

后端 未结 10 2067
一个人的身影
一个人的身影 2020-12-28 11:57

There are two binary trees T1 and T2 which store character data, duplicates allowed.
How can I find whether T2 is a subtree of T1 ? .
T1 has millions of nodes and

10条回答
  •  难免孤独
    2020-12-28 12:36

    I suggest an algorithm, that uses preprocessing:

    1) Pre-process the T1 tree, keeping the list of all possible subtree roots (the cache list will have a millions of entries);

    2) Sort the cached list of roots by the descending order of data, kept in root. You may choose more elegant sorting function, for example, parse a character tree into string.

    3) Use binary search to locate the necessary sub-tree. You may quickly reject subtrees, with the number of nodes, not equal to the T2 number of nodes (or with the different depth).

    Note that steps 1) and 2) must be done only once, then you can test many sub-tree candidates, using the same preprocessed result.

提交回复
热议问题