Algorithm of combining two binary trees?

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

For example:

two trees :

       8                   9
   5        7          4       20
                    30

become one tre

3条回答
  •  囚心锁ツ
    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).

提交回复
热议问题