How to find largest common sub-tree in the given two binary search trees?

后端 未结 4 1631
滥情空心
滥情空心 2020-12-24 04:16

Two BSTs (Binary Search Trees) are given. How to find largest common sub-tree in the given two binary trees?

EDIT 1: Here

4条回答
  •  Happy的楠姐
    2020-12-24 05:09

    The following algorithm computes all the largest common subtrees of two binary trees (with no assumption that it is a binary search tree). Let S and T be two binary trees. The algorithm works from the bottom of the trees up, starting at the leaves. We start by identifying leaves with the same value. Then consider their parents and identify nodes with the same children. More generally, at each iteration, we identify nodes provided they have the same value and their children are isomorphic (or isomorphic after swapping the left and right children). This algorithm terminates with the collection of all pairs of maximal subtrees in T and S.

    Here is a more detailed description:

    Let S and T be two binary trees. For simplicity, we may assume that for each node n, the left child has value <= the right child. If exactly one child of a node n is NULL, we assume the right node is NULL. (In general, we consider two subtrees isomorphic if they are up to permutation of the left/right children for each node.)

    (1) Find all leaf nodes in each tree.

    (2) Define a bipartite graph B with edges from nodes in S to nodes in T, initially with no edges. Let R(S) and T(S) be empty sets. Let R(S)_next and R(T)_next also be empty sets.

    (3) For each leaf node in S and each leaf node in T, create an edge in B if the nodes have the same value. For each edge created from nodeS in S to nodeT in T, add all the parents of nodeS to the set R(S) and all the parents of nodeT to the set R(T).

    (4) For each node nodeS in R(S) and each node nodeT in T(S), draw an edge between them in B if they have the same value AND { (i): nodeS->left is connected to nodeT->left and nodeS->right is connected to nodeT->right, OR (ii): nodeS->left is connected to nodeT->right and nodeS->right is connected to nodeT->left, OR (iii): nodeS->left is connected to nodeT-> right and nodeS->right == NULL and nodeT->right==NULL

    (5) For each edge created in step (4), add their parents to R(S)_next and R(T)_next.

    (6) If (R(S)_next) is nonempty { (i) swap R(S) and R(S)_next and swap R(T) and R(T)_next.
    (ii) Empty the contents of R(S)_next and R(T)_next.
    (iii) Return to step (4). }

    When this algorithm terminates, R(S) and T(S) contain the roots of all maximal subtrees in S and T. Furthermore, the bipartite graph B identifies all pairs of nodes in S and nodes in T that give isomorphic subtrees.

    I believe this algorithm has complexity is O(n log n), where n is the total number of nodes in S and T, since the sets R(S) and T(S) can be stored in BST’s ordered by value, however I would be interested to see a proof.

提交回复
热议问题