Showing posts with label binary. Show all posts
Showing posts with label binary. Show all posts

Monday, 6 May 2013

Create a binary tree using an array

 

Introduction

  Its a reiterate of the same concept of mapping an array to a binary tree. We use this helper routine for creating binary trees used in our problems. So thought about showcasing the code to do that.

Solution

if you have an array like,

arr[] = { 2,3,6,1,8,2,3}

Total: 7 elements. To form a balanced binary tree out of the above array, we have to follow the below index to node mapping for the tree!!

tree-to-index

root = i

left = 2i+1

right = 2i+2

(Assuming starting index of array is 0)

For creating the above balanced tree, you need to do a level order traversal.

We already have some examples (See references). But lets think simple way.

Algorithm:

- queue the first node

- loop

- de-queue from the vector, create a new node + left and right with data.

- push left & right of current node into the queue

- exit when array length is exceeded!!

struct BinTree
{
    int data;
    BinTree *left;
    BinTree *right;
 
    BinTree(int data) {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};
 
BinTree* createBNode(int data)
{
    return new BinTree(data);
}
 
BinTree* arr_to_tree(int *arr, int size)
{
    BinTree *newTree, *root;
    vector<BinTree*> node_list;
    int i=0;
    root = createBNode(arr[0]);
    node_list.push_back(root);
    while(!node_list.empty())
    {
        newTree = node_list.front();
        node_list.erase(node_list.begin());
        if(2*i + 1 >= size)
            break;
 
        newTree->left = createBNode(arr[2*i+1]);
        node_list.push_back(newTree->left);
        if(2*i+2 >= size)
            break;
 
        newTree->right = createBNode(arr[2*i+2]);
        node_list.push_back(newTree->right);
        i+=1;
    }
    return root;
}
 
void main()
{
    BinTree *tree;
    int arr[] = { 2,3,4,6};
 
    tree = arr_to_tree(arr,4);
 
}

 

Reference

http://analgorithmaday.blogspot.in/2011/06/level-order-insert-in-binary-tree.html

Thursday, 15 March 2012

Searching BST

“Scanning through an English dictionary is faster because, you directly go to the indexed character and scan through letter one-by-one to get to the exact text you are searching for”

Preface

  Sorry for not updating for a long period of around 5 months. Really struck up with busy schedules. Now I forgot all the data structures and algorithms. So need to relearn and hence will revisit all my previous posts before going into medium difficulty content.

References

http://analgorithmaday.blogspot.in/2011/03/successor-and-predecessorbst.html

Introduction

  How would you design a search algorithm which does a search through the English dictionary in really fast manner?  Manually, you can easily check a dictionary based on lexicographic ordering. But how would you design a data structure which can naturally allow you to do that? you can do this with a binary search tree.

In previous article, we learnt about Hash Tables(http://analgorithmaday.blogspot.in/2011/10/hash-tables-dictionaries.html) that it is an array index to data mapping. This is a direct mapping hash table which can be generically implemented using binary search trees. If you check the implementations of map and hash_map in C++ STLs, these are implemented using a kind of binary search trees.

Concept

   We decide left or right of the binary search tree based on the value we need to search for. It reduces loops logarithmically.

  Bonus: We can also check how to get the 4th smallest element out of the binary search tree.  This can be done by having an extra field which can calculate the rank of the node.

Rank of a node in BST is number of nodes in the left sub-tree + 1. This is nothing but number of keys less than the current value. This rank is helpful to identify the successor and predecessor easily.

If space is not a constraint, then we should go with ranking the nodes. But if its a constraint, then you should identify the successor of each node

Code

Searching a binary search tree (iteration)

class BST {
public:
    int data;
    BST* parent;
    BST* left;
    BST* right;
};
 
 
BST* createBSTNode(int data)
{
    BST* newNode = new BST();
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    newNode->parent = NULL;
    return newNode;
}
 
void bst_insert(BST*& tree, BST* node)
{
    BST* prev = NULL;
    BST* iter=tree;
    while(iter != NULL)
    {
        prev = iter;
        if(node->data > iter->data)
            iter = iter->left;
        else
            iter = iter->right;
    }
    // found node is parent to our node
    node->parent = prev;
 
    // if prev is NULL
    // then this is the first node
    // change the root NODE
    if(prev == NULL)
        tree = node;
    else {
        // now we need to decide where the node
        // should go: left or right
        if(node->data > prev->data)
            prev->left = node;
        else
            prev->right = node;
    }
 
}
 
BST* convert_arr_bst(int* arr, int size)
{
    BST* tree=NULL;
    for(int i=0;i<size;i++) {
        bst_insert(tree, createBSTNode(arr[i]));
    }
    return tree;
}
 
void main()
{
    BST *tree, *tmp;
    int k = 6;
    bool found = false;
    int arr[]= {2,30,12,10,22,6};
    tree = convert_arr_bst(arr, 6);
    tmp = tree;
    while(tmp && !found)
    {
        if(tmp->data == k) found = true;
        if(tmp->data < k) tmp = tmp->left;
        else {
            tmp = tmp->right;
        }
    }
    if(found == true)
        cout<<"Found"<<endl;
    else
        cout<<"Not Found"<<endl;
}

Searching a binary search tree based on ranks

Will see this in next article about constructing binary search trees with ranks.

Monday, 13 June 2011

Level order insert in a binary tree

“We have seen binary search trees, heaps.. how would you normally create a dynamic tree from a list. Simply, you are given an array, you need to convert it into a binary tree in level order.”

Introduction

    Level order traversal needs a level-by-level movement in a tree. But if you want to recreate the tree from an array in a level-order way. It should be easy. Just you need to fill the elements with the correct formula as we already discussed.

       2i             -----> root

2i+1     2i+2    --> left      right

This is the basis for the level order insert.

Concept

   If you check the level order traversal, many uses stacks. But we should avoid using stacks. Instead, we will use recursion for our case.

  Understanding recursion requires a simple base condition which needs to be repeated for different argument.

     for example, if you have an array,

     arr = {0,1,2,3,4,5,6,7,8,9}

the tree becomes like this,

                  0

           1                    2

    3           4           5      6

7     8     9

For 0, we need to create 1 and 2. For 1, 3, 4. For 3, create 7,8. Similarly for 4, create 9.

This means, you need to do recursion left with left index and right with right index. The end condition is when left or right index is exceeding the size of the array.

Code

Tree *tobj;
 
void level_order_insert(Tree* root, int* arr, int start, int size)
{
    int left = 2*start+1;
    int right = 2*start+2;
 
    if(left > size || right > size)
        return;
 
    if(root == NULL) {
        tobj = createNode(arr[start]);
        root = tobj;
    }
 
    if(root->left == NULL && root->right == NULL) {
        if(left < size)
            root->left = createNode(arr[left]);
        if(right < size)
            root->right = createNode(arr[right]);
    }
    level_order_insert(root->left, arr, left, size);
    level_order_insert(root->right, arr, right, size);
 
}
 
main() {
   int A[] = {0,1,2,3,4,5,6,7,8,9}
   level_order_insert(tobj, A, 0, 10);
}
  • Before root->left = createNode. You need to make sure that left is still < size. This is to handle the border case
  • root->left gets start as all left with all odd numbers
  • root->right gets start as all right with all even numbers.
  • Most of the times you get partially balanced tree with this method.

Monday, 6 June 2011

Reverse in-order traversal of BST

 

Introduction

  How would you get sorted output from a binary tree ? In-order traversal. Recollect all the things that we studied about bst till now,

http://analgorithmaday.blogspot.com/2011/03/binary-search-treeinsertion.html

For BST insertion, we follow in-order principles to construct the nodes. We traverse left/right based on the value and reach the point where the value is greater or lesser. If its less than the root, its left else its right. So, we construct the tree in such a way that, left-root-right is done in reverse from top to bottom.

  But in in-order traversal, we come bottom to top from left->right. This order in which we do the recursion is very important.

  Now, we know that, if we do a in-order traversal of a BST, we get increasing order sorted array. How would you get a decreasing order? How quick sort can do decreasing order sort then ?

Concept

   Decreasing order sort in a quick sort is done by doing partition in a different way. When you partition the array with smaller elements in the left and larger elements at the right, you get increasing order sort. Similarly, if you keep the larger elements to the left and smaller elements to the right, you get decreasing order sort. In Quick sort, its just like changing the > symbol to <.

  But in BST, we have < and > based tree construction done already on memory. In Quick sort, its done on the run. So, how does BST-Sort do descending order sort then ? With in-order traversal.

Don’t mug up that, In-order means left-root-right. :)

You can also do right-root-left. :D It’s just the way of traversal, that’s it!! :)

This is called reverse in-order by some people. So, in a BST, if you do reverse in-order, you get descending order sorted array

Code

#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <iostream>
 
class BST {
public:
    int data;
    BST* parent;
    BST* left;
    BST* right;
};
 
 
BST* createBSTNode(int data)
{
    BST* newNode = new BST();
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    newNode->parent = NULL;
    return newNode;
}
 
void bst_insert(BST*& tree, BST* node)
{
    BST* prev = NULL;
    BST* iter=tree;
    while(iter != NULL)
    {
        prev = iter;
        if(node->data < iter->data)
            iter = iter->left;
        else
            iter = iter->right;
    }
    // found node is parent to our node
    node->parent = prev;
 
    // if prev is NULL
    // then this is the first node
    // change the root NODE
    if(prev == NULL)
        tree = node;
    else {
        // now we need to decide where the node
        // should go: left or right
        if(node->data < prev->data)
            prev->left = node;
        else
            prev->right = node;
    }
 
}
 
BST* convert_arr_bst(int* arr, int size)
{
    BST* tree=NULL;
    for(int i=0;i<size;i++) {
        bst_insert(tree, createBSTNode(arr[i]));
    }
    return tree;
}
 
void ascending(BST* root)
{
    if(root == NULL) return;
    ascending(root->left);
    std::cout<<root->data<<" ";
    ascending(root->right);
}
 
void descending(BST* root)
{
    if(root == NULL) return;
    descending(root->right);
    std::cout<<root->data<<" ";
    descending(root->left);
}
 
 
void main()
{
    int A[] = {4,5,3,2,8,10,1,2};
    BST* root = convert_arr_bst(A, sizeof(A)/sizeof(int));
    ascending(root);
    std::cout<<std::endl;
    descending(root);
    std::cout<<std::endl;
}
  • There are also some BST’s which instead of storing lesser elements at the left and greater at the right, it will do in reverse. Just change the < to > in bst_insert function. You can just do in-order traversal to get the descending order numbers.
  • Now, we understand that, we can mirror a tree using reverse in-order. :) This is also one of the important interview question.
  • Another important thing, you get in a binary search tree root. The median… The root most of the times divides the array into two. If its not, it becomes completely unbalanced.