Algorithm of combining two binary trees?

前端 未结 3 1814
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 21:32

For example:

two trees :

       8                   9
   5        7          4       20
                    30

become one tre

相关标签:
3条回答
  • 2021-01-21 21:43

    The easiest way to merge two binary trees is to take iterate down the left child of one tree until reaching a node without a left child. Then add the other tree's root as the left child. The resulting tree for your example will be:

                8
            5        7
        9
      4  20
    30
    

    However, notice how the resulting tree in this example is very unbalanced. This will result in inefficient operations on the resulting tree, should this be the intention. A better solution is to evenly distribute the nodes of from second tree into the first tree. One way of achieving this is to recursively add the root and left subtree of the second tree to the left subtree of the first tree, and the right subtree to the right subtree. For a slightly more even distribution, randomly select which side to allocate the root to at each step.

    Note that the binary trees here are not binary search trees. Working with BST's is a slightly more interesting case as you have to ensure the resulting tree is also a valid BST. For those interested, here's a solution for that problem: Search for the root value of tree 2 in tree 1. If we reach a dead-end without having found this value, we can just insert tree 2 into the location where the value would be were it in the tree. If we do find the value, then we can replace that node with tree 2. Then take the sub-tree rooted at the node we displaced and insert it into tree 2 using the same algorithm.

    0 讨论(0)
  • 2021-01-21 22:00

    Without more details/constraints, the simplest solution is to take a leaf node of either tree, remove it, and use it as the root to the newly created three.

    In your example:

                 30
        8                   9
    5        7          4       20
    

    This works because your trees don’t appear to follow any particular order, don’t appear to be balanced, nor have any other constraints.

    Since any leaf node will do, this is an O(n) operation in the worst case (traverse one of the trees in any order until we encounter the first leaf, remove it, add child links to both trees’ roots).

    0 讨论(0)
  • 2021-01-21 22:09

    Basic answer would be just to add all the elements in the smaller tree into the bigger tree.

    Another possiblity would be to look into B-Trees (self balancing trees)

    0 讨论(0)
提交回复
热议问题