结合两个二叉树的算法?算法、两个、二叉树

2023-09-11 22:41:14 作者:怀念回不到的从前

例如:

两棵树:

       8                   9
   5        7          4       20
                    30

成为一棵树?

become one tree?

推荐答案

如果没有更多的详细信息/限制,最简单的办法是采取两种树的叶子节点,删除它,并把它作为根到新创建了三个

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.

在您的例子:

             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.

由于任何叶节点会做,这是一个 0 ( N )在最坏情况下(遍历树的一个以任何顺序,直到我们遇到的第一个操作叶,将其删除,添加子链接到这两个目录树的根源)。

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).