简体   繁体   English

我如何合并两个二叉树

[英]How i can merge two binary trees

I have two binary trees and I want to merge them. 我有两个二叉树,我想将它们合并。 My first question is that whether we can merge two binary trees and if yes how efficiently I can perform the merge operations and what are the various ways i can perform the merging operations. 我的第一个问题是,我们是否可以合并两个二叉树,如果可以,我执行合并操作的效率如何,以及执行合并操作的各种方式是什么? ..? ..?

1) Flatten both the trees in to sorted lists. 1)将两棵树放平到排序列表中。
2) Merge the lists from what you got in 1) 2)合并您在1)中获得的列表
3) Construct the tree out of what you got in 2) 3)用2)得到的结果构造树

算法可能会为您提供帮助。

Not considering efficiency this answer may work Algorithm of combining two binary trees? 不考虑效率,这个答案可能有效。结合两个二叉树的算法? . If sorted or balanced, discussion on efficiency in How to merge two BST's efficiently? 如果分类或平衡, 如何在效率上合并两个BST中的效率讨论? and Concatenating/Merging/Joining two AVL trees 串联/合并/联接两个AVL树

A tree is also a graph, so output the edge vertex-pairs (u,v) for each tree, and then union these edge sets, and output the resulting graph. 树也是图,因此输出每棵树的边顶点对(u,v),然后合并这些边集,并输出结果图。

The issue arises with how to map vertices in the one tree to vertices in the other (eg we have edge pair (5,9) in tree 1 and edge pair (5,6) in tree 2, do these 5s correspond to the same vertex ? ). 问题在于如何将一棵树中的顶点映射到另一棵树中的顶点(例如,我们在树1中具有边对(5,9),在树2中具有边对(5,6),这5个边是否对应于同一边顶点?)。

Coming up with a numbering of vertices (perhaps that assigns numbers to each vertex in an incomplete binary tree, as if it were a complete binary tree, so in other words assigns the vertices in any partial binary tree to slots of a hypothetical complete binary tree of which that tree is a subtree), that somehow provides an desirable equivalence is something that works. 提出一个顶点编号(可能是给一个不完整的二叉树中的每个顶点分配数字,就好像它是一个完整的二叉树一样,换句话说,就是将任何部分二叉树中的顶点分配给一个假设的完整二叉树的槽其中那个树是一个子树),以某种方式提供理想的等效性是可行的。

Create a new node and point one tail at the head of one of the trees and point the other tail at the head of the other tree. 创建一个新节点,将一根尾巴指向其中一棵树的头部,将另一根尾巴指向另一棵树的头部。 Perhaps you need to clarify your question to be more specific. 也许您需要澄清您的问题以更具体。 What relationships are you trying to preserve? 您想保持什么关系?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM