Monday, January 16, 2012

A program to check if a binary tree is Binary Search Tree

The basic theory behind this implementation is that the inorder traversal of binary search tree(BST) gives elements in sorted order. So if we traverse the tree and each time we visit next element we get some higher value then we can conclude that the give binary tree is a BST.

bool isBst(node* r)
{
static int no = INT_MAX +1;

if(r == NULL)
return true;
else
{
if(!isBst(r ->left))
return false;
if(r->data > no)
no = r->data;
else
return false;
if(!isBst(r ->right))
return false;
}
return true;
}

Sunday, January 15, 2012

Linear solution of Maximum subarray problem

Maximum subarray problem
Find the contiguous subarray within a one-dimensional array of numbers (containing both positive and negative numbers) which has the largest sum.

#include
using namespace std;
int main()
{
int a[] = {-2,1,-3,4,-1,2,1,-5,4};
int j =0;
int sum = 0, max = 0, str,end,next;
while(j<9) { sum += a[j]; if(sum<0) { sum = 0; next = j+1; } if(sum>max)
{
str = next;
end = j;
max = sum;
}
++j;
}
cout<
cout<<<", "<<
return 0;
}