How i can merge two binary trees - algorithm

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

Related

How many permutations of 1, 2,..., n yield a skew tree? [duplicate]

I know what Binary search tree is and I know how they work. But what does it take for it to become a skewed tree? What I mean is, do all nodes have to go on one side? or is there any other combination?
Having a tree in this shape (see below) is the only way to make it a skewed tree? If not, what are other possible skewed trees?
Skewed tree example:
Also, I searched but couldn't find a good solid definition of a skewed tree. Does anyone have a good definition?
Figured out a skewed Tree is the worst case of a tree.
`
The number of permutations of 1, 2, ... n = n!
The number of BST Shapes: (1/n+1)(2n!/n!n!)
The number of skewed trees of 1, 2, ....n = 2^(n-1)
`
Here is an example I was shown:
http://i61.tinypic.com/4gji9u.png
A good definition for a skew tree is a binary tree such that all the nodes except one have one and only one child. (The remaining node has no children.) Another good definition is a binary tree of n nodes such that its depth is n-1.
A binary tree, which is dominated solely by left child nodes or right child nodes, is called a skewed binary tree, more specifically left skewed binary tree, or right skewed binary tree.

Is it always possible to turn one BST into another using at most O(n) tree rotations?

This earlier question asks whether it's always possible to turn one BST for a set of values into another BST for the same set of values purely using tree rotations (the answer is yes). However, is it always possible to do this using at most O(n) total tree rotations?
Yes, it is always possible to turn one BST into another using at most O(n) tree rotations. This answer follows the same general approach as the other answer by picking some canonical tree shape T* and bounding the number of rotations needed to turn an arbitrary tree into our canonical tree. Then you can turn an arbitrary tree T₁ into another tree T₂ by transforming T₁ into T* and then transforming T* into T₂.
As suggested in comments, you can choose your canonical tree to be a degenerate linked list. For trees of n nodes, this upper bounds the number of rotations needed at 2n−2.
In the paper Rotation Distance, Triangulation, and Hyperbolic Geometry, Daniel Sleator, Robert Tarjan, and William Thurston proved that the rotation distance between any two binary trees of n nodes is at most 2n−6 (better than the bound we get when transforming into a linked list).
At a high level, they did this by introducing a way to represent any binary tree as a polygon triangulation, where a tree rotation has a corresponding triangulation operation. Then, instead of reasoning about binary trees in their usual representation, the paper picks a canonical triangulation and shows how to transform an arbitrary triangulation into their desired one.
The canonical triangulation they chose is one where all diagonals emanate from a single vertex in a fan-like shape, which ends up corresponding to a somewhat unintuitive binary tree shape (a generalization of linked lists that also includes diamond shaped trees consisting of a root, a left child whose right child is a linked list, and a right child whose left child is a linked list).
It's a very cool technique that illustrates the power of isometries in data structures, showing how changing our representation can give us a new way of approaching a problem. Some friends and I recently put together a writeup walking through Sleator, Tarjan, and Thurston's proof if you would like to explore this in more detail.
Yes, this is always possible. I fear that the best I can do right now is give you a silly algorithm that proves it's possible, though I suspect that there must be a much better way to do this.
The Day-Stout-Warren algorithm is an algorithm that, starting with any BST, uses tree rotations to convert it to a perfectly balanced BST. It runs in time O(n) and does O(n) total rotations.
So suppose that you want to turn one tree T1 into another tree T2 using tree rotations. Run Day-Stout-Warren on both trees to convert them to the same balanced tree T*, and record the rotations that you needed to make in both cases. Then you can turn T1 into T2 by first running all the rotations needed to perfectly balanced T1, then running the reverse of the rotations needed to turn T2 into a balanced tree. This turns T1 into T* and then turns T* into T2. Since the Day-Stout-Warren algorithms makes only O(n) total rotations, this too makes only O(n) total rotations.
I feel like there has to be a better way to do this, but I'm not sure off the top of my head how to achieve this. If I think of anything, I'll let you know!

Joining of binary trees

Suppose we have a set of binary trees with their inorder and preorder traversals given,and where no tree is a subtree of another tree in the given set. Now another binary tree Q is given.find whether it can be formed by joining the binary trees from the given set.(while joining each tree in the set should be considered atmost once) joining operation means:
Pick the root of any tree in the set and hook it to any vertex of another tree such that the resulting tree is also a binary tree.
Can we do this using LCA (least common ancestor)?or does it needs any special datastructure to solve?
I think a Binary tree structure should be enough. I don't think you NEED any other special data structure.
And I don't understand how you would use LCA for this. As far as my knowledge goes, LCA is used for knowing the lowest common Ancestor for two NODES in the same tree. It would not help in comparing two trees. (which is what I would do to check if Q can be formed)
My solution in words.
The tree Q that has to be checked if it can be made from the set of trees, So I would take a top-down approach. Basically comparing Q with the possible trees formed from the set.
Logic:
if Q.root does not match with any of the roots of the trees in the set (A,B,C....Z...), No solution possible.
if Q.root matches a Tree root (say A) check corresponding children and mark A as used/visited. (Which is what I understand from the question: a tree can be used only once)
We should continue with A in our solution only if all of Q's children match the corresponding children of A. (I would do Depth First traversal, Breadth First would work as well).
We can add append a new tree from the set (i.e. append a new root (tree B) only at leaf nodes of A as we have to maintain binary tree). Keep track of where the B was appended.
Repeat same check with corresponding children comparison as done for A. If no match, remove B and try to add C tree at the place where B was Added.
We continue to do this till we run out of nodes in Q. (unless we want IDENTICAL MATCH, in which case we would try other tree combinations other than the ones that we have, which match Q but have more nodes).
Apologies for the lengthy verbose answer. (I feel my pseudo code would be difficult to write and be riddled with comments to explain).
Hope this helps.
An alternate solution: Will be much less efficient (try only if there are relatively less number of trees) : forming all possible set of trees ( first in 2s then 3s ....N) and and Checking the formed trees if they are identical to Q.
the comparing part can be referred here:
http://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/

Algorithm to identify if tree is subtree of other tree

I am reading cracking the coding interview, and I have a question on the solution of the following problem:
You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.
The simple solution that it suggests is to create a string representing the in-order and pre-order traversals and check if T2s pre-order/in-order traversal is substring of T1's pre-order/in-order traversal.
What I wonder is why do we need to compare both traversals? And why exactly that two traversals, why not for example in-order and post-order. And mainly won't only one traversal be enough? Say only in-order or pre-order traversal?
One traversal isn't enough. Consider the graphs 1->2->3 and 2<-1->3. If you start with node 1 and do a traversal, you encounter the nodes in the order 1, 2, 3. If you simply create a string showing the pre-order the two give the same result: 1,2,3
On the other hand, if you use a post-order, then the two will give a different result. 3,2,1 and 2,3,1
I bet for any one ordering, you can find two different trees with the same result.
So the question you need to answer for yourself for any other pair you want to look at is: would there be a tree that would give the same order for both traversals? I'm going to leave that as something to think about and come back later to see if you've got it.
I think preorder traversal with sentinel to represent null node is enough.
we can use this approach to serialize/deserialize a binary tree. That means, it is an one-to-one mapping between a binary tree to its preorder+sentinel representation.
After we get strings for both small tree and big tree. then we do a string match using kmp algorithm.
I know people are saying that we have to use both preorder and inorder (or postorder and inorder). but most of them just follow what others are saying, rather than think independently.

Can a non binary tree be tranversed in order?

We are dealing with a Most similar neigthbour algorithm here. Part of the algorithm involves searching in order over a tree.
The thing is that until now, we cant make that tree to be binary.
Is there an analog to in order traversal for non binary trees. Particularly, I think there is, just traversing the nodes from left to right (and processing the parent node only once?")
Any thoughts?
update
This tree will have in each node a small graph of n objects. Each node will have n children (1 per each element in the graph), each of which will be another graph. So its "kind of" a b tree, without all the overflow - underflow mechanics. So I guess the most similar in order traversal would be similar to a btree inorder traversal ?
Thanks in advance.
Yes, but you need to define what the order is. Post and Pre order are identical, but inorder takes a definition of how the branches compare with the nodes.
There is no simple analog of the in-order sequence for trees other than binary trees (actually in-order is a way to get sorted elements from a binary search tree).
You can find more detail in "The art of computer programming" by Knuth, vol. 1, page 336.
If breadth-first search can serve your purpose then you can use that.

Resources