Thursday, October 19, 2017

Binary tree creation and sorting with inorder traversal using python

class node:

    def __init__(self,data):
        self.left = None
        self.right = None
        self.data = data



    def insert(self,data):
        if(data<self.data):
            if self.left is None:
                self.left = node(data)
            else:
                self.left.insert(data)

        elif(data>self.data):
            if self.right is None:
                self.right = node(data)
            else:
                self.right.insert(data)

        else:
            self.data =data


def check_inorder(root):
    if(root is not None ):
        check_inorder(root.left)
        print (root.data)
        check_inorder(root.right)


def main():


    root = node(8)
    root.insert(5)
    root.insert(10)
    root.insert(1)


    check_inorder(root)




main()

Wednesday, October 18, 2017

binary tree creation and inorder traversal for sorting implemented in c++

//// Created by Laxmi Kadariya on 10/17/17.//
#include "iostream"using namespace std;

struct node{
    int key;
    struct node *left,*right;

};

struct node *newNode(int item)
{
    struct node *temp = new node;
    temp->key = item;
    temp->left = NULL;
    temp->right = NULL;
    return temp;


}

struct node*  insert(node *node,int key)
{
    if (node == NULL)
    {
        return newNode(key);
    }
    if(key<node->key)
    {
        node->left = insert(node->left,key);
    }

    else if(key>node->key)
    {
        node->right = insert(node->right,key);
    }

    return node;

}



struct node* create_binary_tree(int arr[],int n)
{
    struct node *root = NULL;
    root = insert(root,arr[0]);
    for(int i=1;i<n;i++)
    {
        insert(root,arr[i]);
    }

    return root;

}

void storeSorted(node *root, int arr[], int &i)
{
    if (root != NULL)
    {
        storeSorted(root->left, arr, i);
        arr[i++] = root->key;
        storeSorted(root->right, arr, i);
    }
}




int main()
{
    int arr[] = {5,4,7,2,11};
    int n = sizeof(arr)/ sizeof(arr[0]);
    int i =0;
    struct node *root = create_binary_tree(arr,n);

    storeSorted(root,arr,i);

    for (int i=0; i<n; i++)
        cout << arr[i] << " ";







}