Wednesday, February 19, 2020

Balanced Binary Tree from sorted array

Create a balanced binary tree from sorted array


#include<iostream>
class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;
};
TreeNode* newNode(int data)
{
TreeNode* node = new TreeNode();
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
TreeNode* createBST(int* arr, int start, int end)
{
if (start > end) return NULL;
int mid = (start + end) / 2;
TreeNode* root = newNode(arr[mid]);
root->left = createBST(arr, start, mid - 1);
root->right = createBST(arr, mid + 1, end);
return root;
}
int main(int argc, char argv[]) {
int arr[] = { 0, 1,2,3,4,5,6,7,8,9 ,10 };
int start = 0, end = sizeof(arr) / sizeof(arr[0]);
TreeNode* root = createBST(arr, start, end-1);
return 0;
}
view raw BalancedBST.cpp hosted with ❤ by GitHub

Array character sequence replacement with another array sequence

In this program a character sequence in an an array is replaced with another.

 Example

 Input string : "mary had a little lamp"

 "little" needs to be replaced with "big"

 Output string : " "mary had a big lamp"
#include "pch.h"
#include <iostream>
class StringFunction {
public:
const char *array;
int *indexArray;
int indexCount;
StringFunction(const char* initString): array(initString),
indexArray(new int[strlen(initString)]) {
}
void printString(const char *str) {
for (size_t i = 0; i < strlen(str); i++) {
std::cout << str[i];
}
std::cout << std::endl;
}
int countString(const char *subStr) {
int mainStrLen = strlen(array);
int subStrLen = strlen(subStr);
int count = 0;
int subStrIndex = 0;
for (int i = 0; i<mainStrLen; i++) {
if (array[i] == subStr[subStrIndex]) {
subStrIndex++;
if (subStrIndex == subStrLen) {
indexArray[count] = i - subStrLen + 1;
count++;
subStrIndex = 0;
}
}
}
indexCount = count;
return count;
}
char *replaceString(const char* stringRemoved, const char* stringAdded) {
countString(stringRemoved);
int diffLen = strlen(stringAdded) - strlen(stringRemoved);
int finalLen = strlen(array) + (diffLen) * countString(stringRemoved);
char *newString = (char *)malloc(sizeof(char)*finalLen);
int mainIndex = 0;
int index = 0;
for (int i = 0; i < finalLen; i++) {
if (i == (indexArray[index] + (index*diffLen))) {
for (int j = 0; j < strlen(stringAdded); j++) {
newString[i + j] = stringAdded[j];
}
index++;
i = i + strlen(stringAdded);
mainIndex = mainIndex + strlen(stringRemoved);
}
newString[i] = array[mainIndex++];
}
return newString;
}
};
int main(int argc , char argv[])
{
StringFunction strClass("Mary had a little lamb, lamb was little, Mary was little");
std::cout << strClass.replaceString("little", "huge") << std::endl;
}