结合两个二叉树的算法? [英] Algorithm of combining two binary trees?

查看:127
本文介绍了结合两个二叉树的算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

两棵树:

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

这篇关于结合两个二叉树的算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆