How i can merge two binary trees

后端 未结 5 914
醉话见心
醉话见心 2020-12-18 03:39

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 operati

相关标签:
5条回答
  • 2020-12-18 03:46

    This algorithm might help you.

    0 讨论(0)
  • 2020-12-18 03:49

    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

    0 讨论(0)
  • 2020-12-18 04:02

    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?

    0 讨论(0)
  • 2020-12-18 04:05

    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 讨论(0)
  • 2020-12-18 04:10

    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)

    0 讨论(0)
提交回复
热议问题