Thursday, October 8, 2015

#codingquestions
Tree operations
        typedef struct _node{
  int value;
  node* left;
  node* right;
 }node;
 node* treeMinimum(node* root)
 {
  node* current = root;
  while(current->left)
   current = current->left;
  return current;
 }
 node* treeParent(node* root, node* z)
 {
  node* parent = NULL;
  node* current = root;
  while(current){
   if(current == z) return parent;
   if (current->value < z->value){
    parent = current;
    current = current->right;
   }else{
    parent = current;
    current = current->left;
      }
  }
  // z was not found in tree
  if (parent != NULL
      && parent->left != z
      && parent->right != z)
   parent = NULL;
  return parent;
 }
 node* treeSuccessor(node*root, node* z)
 {
  if (z->right)
   return treeMinimum(z->right);
  node* y = treeParent(root, z);
  while (y && z == y->right)
  {
   z = y;
   y = treeParent(root, y);
  }
  return y;
 }
 node* treeDelete(node*root, node* z)
 {
  node* y = NULL;
  node* x = NULL;
  node* px = NULL;
  node* py = NULL;
  if (z->left == NULL || z->right == NULL)
   y = z;
  else
   y = treeSuccessor(root, z);
  if (y->left != NULL)
   x = y->left;
  else
   x = y->right;
  //if (x != NULL)
  // px = py;
  py = treeParent(root, y);
  if (py == NULL)
   root = x;
      // root->value = x->value;
      // root->left = x->left;
      // root->right = x->right;
      // delete x;
  else if (y == py->left)
      py->left = x;
  else
   py->right = x;
  if (y != z)
   z->value = y->value;
  return y;
 }
 bool exists(node* root, int val)
 {
  if (root == NULL) return false;
  node* current = root;
  while(current)
  {
   if (current->value == val) return true;
   if (current->value < val) current = current->right;
   else current = current->left;
  }
  return false;
 }

 void readElementsInOrder(int* pValue, int* pCount)
 {
  char buffer[255] = {'5',' ', '3', ' ','2', ' ', '4', ' ', '7', ' ', '6',' ', '8'};
  sscanf(buffer, "%s");
  char seps[] = " ";
  char* token = NULL;
  //int values[255];
  int* values = pValue;
  token = strtok(buffer, seps);
  int i = 0;
  while (token != NULL)
  {
   values[i] = atoi(token);
   token = strtok(NULL, seps);
   i++;
  }
  *pCount = i;
 }

 for (int i = 0; i < count; i++)
 {
  printf("%d", values[i]);
 }

5324768

No comments:

Post a Comment