convert Binary tree to Binary Search Tree inplace using C - c

Without using any extra space convert Binary Tree to Binary Search tree.I came up with the following algo but It doesn't work.
BTtoBST(node *root)
1.if the root is NULL return
2.else current=root
3.if (current->left > current) swap(current->left , current)
4.if (current->right < current) swap(current->right , current)
5.current=current->left
6 go to 3 if current!=NULL else go to 4
7.current=current->right
Thanks in advance
PS:I saw this link but was not of much help!!
Convert Binary Tree -> BST (maintaining original tree shape)

You can swap the nodes including subtrees (not only the node content) like in an AVL Tree http://en.wikipedia.org/wiki/AVL_tree
Just keep swapping as long as BST constraints are violated, restarting deep first search from root after each swap.

Perform a post-order (bottom up) traversal of the tree, taking the nodes that are visited and inserting them into a BST.
Does "without any extra space" preclude recursion?
If not, then something like:
# top level call passes null for bst
bt_to_bst (root, bst)
# nothing to add to bst; just return it
if null(root) -> return bst
# if this is a leaf node, stick it into the BST
if null(root->left) && null(root->right)
return bst_insert(bst, root)
# otherwise add all of left subtree into the bst and then the right tree
bst = bt_to_bst (root->left, bst);
return bt_to_bst (root->right, bst);
bt_to_bst is a filtering operation; it takes an existing bst and returns a new one with the given node added to it.
Adding a leaf node to the bst is safe because we will never visit it again, so we can overwrite its left and right pointers.

Related

Find and delete wrong node in a BST in C

I have a C problem which i need to check if a given Tree is a Binary Search Tree or not and then find which node is incorrect and delete it (from the problem definition, it will always be just one wrong node). For instance:
10
|
|
9 12
| |
| |
7 3 11 14
In this tree, element 3 is incorrect and should be deleted. In case of given tree is already a BST, algorithm should do nothing. I'm trying to adapt a solution from CodeForGeeks which verifies if a tree is a BST or not to instead returning a boolean, returning a pointer for the node which is wrong, but this isn't working well. Here's the method i came up with:
NODE* verifyBinaryTree(NODE* root, NO** previous){
if(node != NULL){
NODE* left= verifyBinaryTree(root->left, previous);
if(left != NULL){
return left;
}
if(*previous && root->data <= (*previous)->data) return root;
*previous = root;
return(verifyBinaryTree(root->right, previous));
}
return NULL;
}
I would enjoy if someone could help me to find the right logic behind this problem.
Here is an easy way to approach this problem . If you do inorder traversal on a valid BST , you will get the nodes sorted in increasing order .
You can do this inorder traversal and after storing them serially in a data structure (perhaps array) , check if the adjacent elements are not in increasing order . If you find such elements , you need to delete them .

How can I construct a strict binary tree when the only information given is post order traversal?

Previously I asked how to get the pre-order of a tree when I am only given post-order traversal. However, now I'm curious as to how one would build a strict binary tree (strict binary tree meaning a node either has two children or no children) when only given post order traversal.
Some example data I am dealing with :
7 8 2 // 8,2 are dimensions stored in the node, likewise for other nodes)
6 4 8
3 1 5
A
B
I know what the tree is supposed to look like:
B
/ \
7 A
/ \
6 3
But I am lost on how to write a function that would actually build this tree (and store in the information in the nodes) from the information given (post order traveral.) How can I do this?
Creating a full binary tree from the postorder is like creating a syntax tree from Reverse Polish Notation with only binary operators. The branches are the operators, the leaves are the values. (You must be able to tell which is which. In your axample, brenches are letters, leaves are numbers.)
You can process the data as it comes. If it is a leaf, create a node and push it on the stack. It is is a branch, create a node, pop its right and left branches off the stack and push the new node. If the received data is valid, you should have a single node on the stack. That's the root of your tree.
So, in pseudo-ish C code:
Node *head = NULL;
while (!stream_empty()) {
int data = stream_get();
if (is_leaf(data)) {
if (nstack == MAX) fatal("Stack overflow!");
stack_push(make_node(data));
} else {
if (stack_size < 2) fatal("Stack underflow!");
Node *node = make_node(data);
node->right = stack_pop();
node->left = stack_pop();
stack_push(node);
}
}
if (nstack != 1) fatal("Ill-formed full binary tree!");
head = stack[0];
Stack overflow occurs when the tree is deeper than the stack size. Stack underflow or leftover nodes at the end occur when the input data is ill-formed.
Here's a full working example on ideone.
[Note: I've completely rewritten my answer, because the OP has specified new requirements. I had also based my original answer of a answer I gave to OP's previous question. I think that the present approach is more elegant. Whatever that means. :)]

How does recursion works in a binary search tree?

Binary search tree algorithms usually use recursion, and I'm having a hard time with it.
This is a code which converts the tree into its mirror image .
void mirror_image(struct tree* node1)
{
if (node1==NULL)
return;
else
{
struct tree *temp;
mirror_image(node1->left);
mirror_image(node1->right);
temp=node1->left;
node1->left=node1->right;
node1->right=temp;
}
}
How does this work?
Basically you are creating new tree with changing its right and left node. pointers because you are making changes in adresses. first you are assigning value of left node to temp pointer variable. Then value of right node into left node. And at last the value in temp is shifting to right node. its like swapping.
So, it scans the left childs trees using
mirror_image(node1->left);
and right childs tress using
mirror_image(node1->right);
on reaching the end when
if (node1==NULL)
return;
it interchanges them using the swap procedure:
temp=node1->left;
node1->left=node1->right;
node1->right=temp;
I'd suggest try with a small binary tree, see it yourself on paper.

Printing in ascending order (sorting) from AVL trees

I need to define a main function that reads integers and prints them back in ascending order.
For example, if the input contains
12
4
19
6
the program should output
4
6
12
19
I need to use trees to do this however. I'm given the use of two functions insertavl, and deleteavlat my disposal. Their defintions are like so... http://ideone.com/8dwlU basically when deleteavl is called it deletes the node, and rebalances the tree accordingly
... If interested thier structures are in: http://ideone.com/QjlGe.
I've gotten this so far:
int main (void) {
int number;
struct node *t = NULL;
while (1 == scanf("%d",&number)) {
t = insertavl(t, number);
}
while (t != NULL){
printf("%d\n",t->data);
t = deleteavl(t, t->data);
}
}
But this doesn't print them in ascending order. Any suggestions would be helpful? thanks in advance!
Hint: in-order traversal on a BST is iterating the elements in ascending order.
Since an AVL Tree is a specific implementation of a BST, it also applies here.
EDIT: Explanation - why is this property of in-order traversal on a BST correct?
In in-order trvaersal, you access [print] each node after you accessed all the nodes in the left subtree. Since in a BST the root is bigger then all the nodes in the left subtree, it is what we wanted.
Also, in in-order traversal, you access each node before accessing all elements in the right sub-tree, and again, since it is a BST - this is exactly what we want.
(*)Note: This is not a formal proof, just an intuitive explanation why it is true.

inorder traversal in BST

how to keep track of previous node in recursive inorder binary search tree traversal?
eq...
in finding floor of any no... in bst ...iam trying to find the first number in bst which larger than given value ...and at that point printing the data of prev node which is either equal to or less then given value as it is inorder traversal...
so why question is how we can keep track of previous node in bst in
recursive inorder traversal??
(Aside: It doesn't sound like you're asking for an in-order traversal, but rather a binary search function that returns the greatest node that is no greater than the query.)
The two most common ways of keeping track of stuff like this in a recursive algorithm are to either pass it down as a parameter, or to return back up to it. (Either way you're storing information about the past on the stack.)
In your case it's probably cleanest to do the latter. eg:
Node* floor_node(int x, Node *subtree) {
if (subtree) {
if(subtree->value > x) {
return floor_node(x, subtree->left);
} else {
return floor_node(x, subtree->right) || subtree;
}
} else {
return subtree;
}
}
Binary tree recursion works by going down the left tree and then the right. Inorder/preorder/postorder are a convention that is determined merely by the ordering of some local action in the recursive procedure: the timing of the "visiting" of the current node itself with regard to the two recursive calls.
How you can get the next node is to have the recursion return it.
When you recurse into a tree, the last node visited in "inorder" is simply the rightmost node! Therefore, your recursion must simply return the rightmost node.
Furthermore, if a tree T as a whole has some previous node P, then the left subtree of T, namely left(T) also has the same previous node P. P is the predecessor of the leftmost node of T.
Moreover, the previous node with respect to right(T) is the node T itself.
So when recursing into left(T) we can simply pass down the same predecessor that was given to us, and when recursing into right(T) we pass ourselves as the predecessor.
Pseudocode:
# a recursive function that is given its previous node,
# and returns the rightmost node
recurse_with_previous (tree previous-in):
# skip empty link. No leaf to see here!
# previous-in is the rightmost node still
if null(tree)
return previous-in
# if we are at a leaf, then that leaf is rightmost
if leaf(tree)
print "visiting leaf node " tree " with previous node " previous-in
return tree
# the previous node (previous-in) of this tree is actually the left
# subtrees previous node, so we just pass that parameter down
previous = recurse_with_previous (left(tree) previous-in)
# inorder visit: visit this node between the subtrees
print "visiting " tree " with previous node " previous
# now the right subtree. what is ITS previous? Why, we are!!!
# we return whatever this returns causing the return value
# to be the rightmost node.
return recurse_with_previous (right(tree) tree)
# how to call
recurse_with_previous(some-tree nil)

Resources