Thursday, May 26, 2016

Check is a tree is a binary search tree

#include <iostream>
using namespace std;

struct Node
{
    int data;
    struct Node *left;
    struct Node *right;
};

struct Node * newNode(int data)
{
  // Allocate memory for new node
  struct Node * node = (struct Node*)malloc(sizeof(struct Node));

  // Assign data to this node
  node->data = data;

  // Initialize left and right children as NULL
  node->left = NULL;
  node->right = NULL;
  return(node);
}

int isLeftSubtreeLesser(Node * root, int data) {
if (root->data > data) {
return 0;
}
if (isLeftSubtreeLesser(root->left, data) && isLeftSubtreeLesser(root->right, data))
return 1;

return 0;
}

int isRightSubtreeGreater(Node * root, int data) {
if (root->data <= data) {
return 0;
}
if (isRightSubtreeGreater(root->left, data) && isRightSubtreeGreater(root->right, data))
return 1;

return 0;
}

int isBinarySearchTree (Node * root) {
if (root == NULL) {
return 1;
}

if (isLeftSubtreeLesser(root->left, root->data) && isRightSubtreeGreater(root->right, root->data)
&& isBinarySearchTree(root->left) && isBinarySearchTree(root->right)){
return 1;
} else {
return 0;
}
}

int main() {

struct Node *root = newNode(1);

  root->left        = newNode(2);
  root->right       = newNode(3);
  root->left->left  = newNode(4);

isBinarySearchTree(root);
return 0;
}

Wednesday, May 18, 2016

Permutations of a string with repeatitions

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>

using namespace std;

void permute(char * str, int len, char * data, int index) {

for (int i = 0; i < len; i++) {
data[index] = str[i];
if (index == len - 1) {
cout<<data<<"\n";
} else {
permute(str, len, data, index +1);
}
}
}

void allLexicographicString(char * str) {

int len = strlen(str);
sort(str, str + len - 1);
char * data = new char[len];
permute(str, len, data, 0);
}

int main() {

char str[] = "ABC";
allLexicographicString(str);
return 0;
}

Permutations of a String without repeatition

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

void permute (char * a, int l, int r) {

if (l == r) {
cout<<a<<"\n";
} else {
for (int i = l; i<=r; i++) {
swap ((a + l), (a + i));
permute(a, l+1, r);
swap ((a + l), (a + i));
}
}
}

int main() {
// your code goes here
char str[] = "ABC";

int n = strlen(str);
    permute(str, 0, n-1);

return 0;
}