Can a non binary tree be tranversed in order? - algorithm

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.

Related

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.

What is the difference between breadth first searching and level order traversal?

I don't need code, just an explanation. My textbook says
level order: each node at level i is processed before any node at level i+1
My understanding of breadth first searching is that you explore nodes nearest the root first, starting from the left? How is this any different? Is this a square and rectangle sort of situation?
For a 'proper' tree (see below), it's the same thing, at least by most definitions. Like Wikipedia, for example:
Breadth-first
See also: Breadth-first search
Trees can also be traversed in level-order, ...
... a breadth-first (level-order) traversal ...
Well, at least level-order traversal is the same as breadth-first traversal. There are many reasons to traverse something, it doesn't just have to be to search, as breadth-first search seems to imply, although many (or most) don't make that distinction and use the terms interchangeably.
The only time I'd personally really use "level-order traversal" is when talking about in-, post- and pre-order traversals, just to follow the same "...-order traversal" format.
For a general graph, the concept of a 'level' may not be well-formed (although you could just define it as the (shortest) distance from the source node, I suppose), thus a level-order traversal may not be well-defined, but a breadth-first search still makes perfect sense.
I mentioned a 'proper' tree above (which is a totally made up sub-classification, in case you were wondering) - this simply means 'level' is defined as you'd expect - each edge increases the level by one. However, one may be able to play around with the definition of 'level' a bit (although doing this may not be widely accepted), in essence allowing edges to jump over levels (or even have edges between nodes on the same level). For example:
level
1 1
/ \
2 / 3
/ /
3 2 4
So the level-order traversal would be 1, 3, 2, 4,
while the breadth-first traversal would be 1, 2, 3, 4.
What is the difference between breadth first searching and level order traversal?
DEFINITION: "The level-order of an ordered tree is a listing of the vertices in the top-to-bottom, left-to-right order of a standard plane drawing of that tree".
Please bear in mind that when we are discussing level-order we are talking exclusively about Trees, and not graphs in general.
And we can be even more specific and say we are discussing about Rooted-Trees.
DEFINITION: "Rooted Tree is a tree with a designated vertex called the root. And each edge is considered to be directed away from the root. Thus, the rooted tree is a directed tree such that the root has indegree = 0 (so no incoming edges)".
*Its important to make the distinction because its this property that allows for the recursive implementation of trees.
Furthermore, level-order traversal would not make sense about a Graph (the tree is one specific type of a graph (no cycle and connected)).
So for graphs we use BFS and the BFS we use for trees has been termed "level-order traversal" (because since we are talking about rooted-trees, then levels do make sense. Whereas in a graph they would not make sense, due to the absence of the root).
Conclusion: Level-order traversal is the breadth-first-search for the case of the specific graph structure named: Tree (specifically Rooted-Trees)
we use level order traversal for trees because in trees there is no cycle and once a node is visited, it is not gonna visit again
but in graphs, its is not so.
Graph can be cyclic as well
and if a graph is cyclic, as per level order if a node is visited, it doesnt check it is visited or not and again it will traverse the same node infinite times. and program will continue to traverse because of cycle.
So we use BFS or DFS in case of graph.
In general, traversing is a technique of visiting all the elements only once in a data structure. The process of getting,modifying,checking the data of all nodes in a tree is called Tree Traversal.
Search means looking for an item. It does not mean that you are going to visit all nodes. Let's say you are looking for the first node whose value is less than 10, once you find 10, you exit searching.

Tree traversal and serialization

I am trying to get straight in my head how tree traversals can be used to uniquely identify a tree, and the crux of it seems to be whether the tree is a vanilla Binary Tree (BT), or if it also has the stricter stipulation of being a Binary Search Tree (BST). This article seems to indicate that for BT's, a single inorder, preorder and postorder traversal will not uniquely identify a tree (uniquely means structure and values of keys in this context). Here is a quick summary of the article:
BTs
1. We can uniquely reconstruct a BT with preorder + inorder and postorder + inorder.
2. We can also use preorder + postorder if we also stipulate that the traversals keeps track of the null children of a node.
(an open question (for me) is if the above is still true if the BT can have non-unique elements)
BSTs
3. We cannot use inorder for a unique id. We need inorder + preorder, or inorder + postorder.
Now, (finally) my question is, can we use just pre-order or just post-order to uniquely identify a BST? I think that we can, since this question and
answer
seems to say yes, we can use preorder, but any input much appreciated.
I can't tell what's being asked here. Any binary tree, whether it's ordered or not, can be serialized by writing out a sequence of operations needed to reconstruct the tree. Imagine a simple stack machine with just two instructions:
Push an empty tree (or NULL pointer if you like) onto the stack
Allocate a new internal node N, stuff a value into N, pop the top two trees off the stack and make them N's left and right children, and finally push N onto the stack.
Any binary tree can be serialized as a "program" for such a machine.
The serialization algorithm uses a postorder traversal.
Okay, you can use preorder only to identify a tree. This is possible because only in preorder traversal does the id-of-current-node comes before the ids of children. So you can read the traversal output root-to-leaves.
You can check http://en.wikipedia.org/wiki/Tree_traversal#Pre-order to confirm
So you can consider a preorder traversal as a list of insertions into a tree. Because the tree insertion into BST is deterministic, when you insert a list of values into an empty tree, you always get the same tree.

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

Resources