开发者

How i can merge two binary trees

开发者 https://www.devze.com 2023-03-30 11:54 出处:网络
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 variou

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. .开发者_如何学Go.?


1) Flatten both the trees in to sorted lists.
2) Merge the lists from what you got in 1)
3) Construct the tree out of what you got in 2)


This algorithm might help you.


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? and Concatenating/Merging/Joining two AVL trees


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?


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.

The issue arises with how to map vertices in the one tree to vertices in the other (e.g. 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 ? ).

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消