Insert element to binary tree at specific position - c++

It might be an newbie question but I am struggling to get an answer to this question. Consider an binary tree(not binary search tree) like this:
root
child1 child2
child3 child4
I need to add "child5" at the left child of "child2". How an I do that? I know the way to add nodes for binary search tree. Snapshot of the same is something like this:
if (newNode->val < root->data) {
-> pick left node
} else {
-> pick right node
}
Since tree is not an BST, this solution would not be correct.
An pictorial representation of what I am trying to say:
1
2 3
4 5
In above tree, '6' should be added as left of '3'.

Okay. I think answer to this would be something like this:
Little tweak in BFS would be required. When you pop up the items from the queue, check if any of the children is empty. The first empty child slot is the place you want to add to.

Related

Find all possible paths in depth first search in graph

I am trying to find all the possible paths from one node in my graph that will visit all other nodes in the graph. I want the function to produce all possibilities of paths in my n*m graph. Each node in my graph has a vector of all neighbors nodes and a Boolean that check if the node is visited or not.
example:
a b
c d
will produce:
abcd
abdc
acbd
...
I tried the solution in this answer, but only return one path. How can I produce all possible paths?
It seems like in some situations by your description you could have infinite paths and a path of infinite length because you didn't specify that nodes couldn't be revisited.
You should implement depth first search and pass a reference to an array of marked (visited) nodes in your recursive DFS method assuming that you have a count of the number of nodes in your graph. After you visit each node, before you leave that node make sure you set it to false again so that it can be reaccessed via another node.
The implementation of this algorithm is really going to depend on how you implemented your graph structure and without the details all I can do is speculate that you have a linked structure with an adjacency list representing the different nodes. I also have no idea how the different nodes map to characters so that is another detail I have to speculate, but say that the nodes are represented by integers.
You need to pass into a DFS method the following: array of marked nodes, a linked list which contains the path information, starting node, (i.e, current node) and final node
void printAllPaths(LinkedList<Integer> currentPath, boolean[] marked, int current, int last){
for( all nodes adjacent to current, node ){
if(node == last){
currentPath.addLast(last);
System.out.println(currentPath);
currentPath.removeLast();
}else if(!marked[node]){
currentPath.addLast(node);
marked[node] = true;
printAllPaths(currentPath, marked, node, final);
marked[node] = false;
currentPath.removeLast();
}
}
}
This will be the basic idea of the code. I apologize if it doesn't compile in advance, but this should print out all of the paths.

Delete Node of BOOST Spirit AST Tree

I have a question concerning Abstract Syntax Trees generated with Boost Spirit Library.
I've found many informations about deleting nodes and subtrees in a Binary Search Tree, but I cannot find the same information for ASTs. I have a node in an AS-Tree, and this node is root to a subtree of a complete tree. Now I want to delete the node and all of its children.
I don't know how to do it, and the Boost Spirit Documentation didn't help either.
Has anyone got any tips for me?
The Tree is generated with (Boost 1.46.1):
tree_parse_info<> info = ast_parse(expression.c_str(), parser, skipparser);
And the Expression is something like this:
(variable_17 OR variable_18) AND function( variable_17) <= 30 OR function( subkey_18) <= 30
I use
tree_match<iterator_t>::tree_iterator tree_it = info.trees.begin();
to get the beginning of the tree, and then I do check if one of the subtrees is redundant (doensn't have anything to do with the deleting itself). `Then I traverse through the tree using
tree_match<iterator_t>::tree_iterator children_it = tree_it->children.begin()
and calling the same function with its children (recursive). I can't post the complete code,but that's the most important part of it. I thought, that i can traverse to the leafnodes of a redundant subtree, and set them to null, or something like this. And then I go up the tree again, and delete all other children one after another. However, nothing has worked so far.
An example for traversing the tree: The Traversing
It's the answer.
If I can't delete any nodes, does anyone has an idea, how to create a new tree, based on the existing one, skiping the redundant parts of it.

AVL Insert and balance loop

I am implementing AVL Trees in C++ on my own code but this problem is more about understanding AVL trees rather than the code itself. I am sorry if it doesn't fit here but I have crawled through the Internet and I have still not found a solution to my problem.
My code works as expected with relatively small inputs (~25-30 digits) so I suppose it should work for more. I am using an array in which I hold the nodes I have visited during Insertion and then using a while loop I am raising the heights of each node when needed, I know that this procedure has to end when I find a node whose heights are equal (their subtraction result is 0 that is).
The problem is when it comes to balancing. While I can find the Balance Factor of each node and balance the tree correctly I am not sure if I should stop adjusting the heights after balancing and just end the Insertion loop or keep going until the condition is meant, and I just can't figure it out now. I know that during deletion of a node and re-balancing the tree I should keep checking but I am not sure about Insertion and balancing.
Anyone can provide any insight to this and perhaps some documentation?
If you insert only one item at a time: Only one (single or double) rotation is needed to readjust an AVL tree after an insertion throws it out of balance. http://cis.stvincent.edu/html/tutorials/swd/avltrees/avltrees.html You can probably prove it by yourself after you know the conclusion.
Just for reference of future readers there is no need to edit the heights of the nodes above the node you balanced if you have implemented the binary tree like my example:
10
(1)/ \(2)
8 16
(1)/ \(0)
11
(Numbers in parenthesis are the height of each sub tree)
Supposing than on the tree above we insert a node with data=15 Then the resulting subtree is as following:
10
(1)/ \(2)
8 16
(1)/ \(0)
11
(0)/ \(1)
15
Notice how previous heights of sub trees are not yet edited. After a successful insertion we run back through the insertion path, in this case its (11, 16, 10). After running back through this path we edit the heights when needed. That means the left height of the sub tree of 16 will be 2 while it's right height of sub tree is 0 resulting in an imbalanced AVL tree. After balancing the tree with a double rotation the sub tree is:
15
(1)/ \(1)
11 16
So the subtree height is maximum 1, as it was before, therefore heights above the root of this subtree haven't altered and the function changing the heights must return now.

Binary tree Breadth-first search

I'm using OCaml. I have type:
type 'a bt = Empty | Node of 'a * 'a bt * 'a bt;;
Also I have example BST:
let tree = Node(1,Node(2,Node(4,Empty,Empty),Empty),Node(3,Node(5,Empty,Node(6,Empty,Empty)),Empty));
I need to write function: breadthBT : 'a bt -> 'a list which will be Breadth-first search traversal. For above example tree it should returns [1; 2; 3; 4; 5; 6]
How to write that function? I can write only following function which uses DST :
let rec breadthBT tree =
if tree=Empty then []
else let Node(w,l,r)=tree in (w::breadthBT l)#breadthBT r;;
Above function returns (for example tree) [1; 2; 4; 3; 5; 6]. But I can't write function which uses BFS. Could you help me?
It is not a compilable solution. Just a tip.
You should iterate from top level root node to deep level nodes. Let our function receives accumulator for the answer and list of nodes (your 'a bt values) as second parameter. You can map this list by getting first element of triple and than you receive next part of answer. Also you need to evaluate next level of tree. For every node there are at most two descendants. You can map your list and apply _a_function_to receive list of descendants. It will be next level of your tree. And than --- recursion.
A will not specify this _a_function_. Try to study what is concatMap in google.
Happy hacking!
Imagine you stick your nose to the tree. Is it possible to traverse the tree in the breadth-first manner without bookmarking positions in your notepad? No, because the order can make you jump from one branch to another unrelated branch. So you need a notepad with "remaining positions to visit". You pick the next remaining position from the notepad and jump to it blindly. Since you erase visited positions from the notepad, you are at a node you have not visited yet. And since you cannot get up the tree without visiting intermediate nodes, you haven't visited the two nodes now above you. But you resist the instinct to climb the branches directly -- heck, this is breadth first order. You do not want to forget about these two unvisited nodes, so you want to put them into the notebook. Where do you put them, in front of the notebook or on its back? On the back of course, otherwise you would pick one of them immediately and that's what we want to avoid. Et voila: your notepad is a FIFO queue of nodes, which you keep (i.e. pass) around as an accumulator, but also consume to pick a subtree to visit.

Adding data to binary tree

I need help with adding data to a tree. For example if i have 7+8*9-18/(1+2), how am I supposed to add it to a binary tree in a way that i can compute the result using a binary tree. I am beginner in learning tree structures so I am not very familiar with it.
After converting the post fix expression to infix, follow the below steps to construct a tree.
If it is number, add it to add to the stack.
If is is an operator, make the operator as parent node,
pop the element and make it as right child to the parent node,
pop the element and make it as left child to the parent node
and add the parent node to the stack.
See How to write an evaluator for a string like "(1+3 * ( 5 / 4)) and get a numeric result and the Shunting Yard Algorithm