Adding data to binary tree - c++

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

Related

Insert element to binary tree at specific position

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.

unbalanced avl tree check function

I'm implementing an AVL tree and wrote that function that will calculate the balance factor of a given tree:
int avlTree::balanceFactor(avlNode *tree){
return height(tree->left) - height(tree->right);
}
but it seems like while indeed return me the right balance factor of the tree, it won't let me determine weather the tree is AVL balanced, because according to defintion, for every sub tree the balance factor should be checked. i.e that tree:
would have, according to the function a balance factor of 0, which doesn't give me a lot when it comes to balancig the tree. what can i add?
Your balanceFactor function is correct. You just apply it to nodes starting from the root, going down the chain of unbalanced nodes, as described here, for example.

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.

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.

Searching data stored in a tree

I have this data that is hierarchical and so I store it in a tree. I want to provide a search function to it. Do I have to create a binary tree for that? I don't want to have thousands of nodes twice. Isn't there a kind of tree that allows me to both store the data in the order given and also provide me the binary tree like efficient searching setup, with little overhead?
Any other data structure suggestion will also be appreciated.
Thanks.
EDIT:
Some details: The tree is a very simple "hand made" tree that can be considered very very basic. The thing is, there are thousands of names and other text that will be entered as data that I want to search but I don't want to traverse the nodes in a traditional way and need a fast search like binary search.
Also, importantly, the user must be able to see the structure he has entered and NOT the sorted one. So I cant keep it sorted to support the search. That is why I said I don't want to have thousands of nodes twice.
If you don't want to change your trees hierarchy use a map to store pointers to vertexes: std::map<SearchKeyType,Vertex*> M.
Every time when you will add vertex to your tree you need to add it to your map too. It's very easy: M[key]=&vertex. To find an element use M.find(key);, or M[key]; if you are sure that key exists.
If your tree has duplicate keys, then you should use a multimap.
Edit: If your key's size is too big, than you can use pointer to key instead of key:
inline bool comparisonFunction(SearchKeyType * arg1,SearchKeyType * arg2);
std::map<SearchKeyType *, Vertex *, comparisonFunction> M;
inline bool comparisonFunction(SearchKeyType * arg1,SearchKeyType * arg2)
{
return (*arg1)<(*arg2);
}
to search Element with value V you must write following:
Vertex * v = M[&V]; // assuming that element V exists in M