예제 #1
0
PTreeNode findOrInsert(BinaryTree bt, NodeData d)
{
    PTreeNode pCurr, pNode;
    int cmp;

    if (bt.pRoot == NULL) {
        pNode = newTreeNode(d);
        pNode->parent = NULL;
        return pNode;
    }

    pCurr = bt.pRoot;

    while ((cmp = strcmp(d.word, pCurr->data.word)) != 0) {
        if (cmp < 0) {
            if (pCurr->left == NULL) {
                pCurr->left = newTreeNode(d);
                pCurr->left->parent = pCurr;
                return pCurr->left;
            }

            pCurr = pCurr->left;
        } else {
            if (pCurr->right == NULL) {
                pCurr->right = newTreeNode(d);
                pCurr->right->parent = pCurr;
                return pCurr->right;
            }

            pCurr = pCurr->right;
        }
    }

    return pCurr;
}
예제 #2
0
TNODE *makeFlatTree(const TEXTNODE *list)
{
	const TEXTNODE *listnode = list;
	
	qsort(prims, sizeof(prims)/sizeof(prims[0]), sizeof(PRIMTYPE), cmpPrim);
	if (DEBUG)
		printf("Making Syntax Tree...\n");
	//create command tree from list array
	TNODE *tree = NIL;
	TNODE *current = NIL;
	//split text into expressions and commands...
	while (listnode)
	{
		//printf("List[%d]: %s (%s)\n", i++, listnode->text, dispPrimType(listnode->ntype));
		if (tree == NIL)
		{
			current = tree = newTreeNode(listnode);
		}
		else
		{
			current = setNextNode(current, newTreeNode(listnode));
		}
		listnode = listnode->next;
	}
	return tree;
}
예제 #3
0
TNODE *makeFlatTree(TEXTNODE *list)
{
  TEXTNODE *listnode = list;
  TEXTNODE *next;

  //no need to qsort, already presorted...
  qsort(prims, sizeof(prims)/sizeof(prims[0]), sizeof(PRIMTYPE), cmpPrim);
  if (DEBUG)
    Serial.print("Making Syntax Tree...\n");
  //create command tree from list array
  TNODE *tree = NIL;
  TNODE *current = NIL;
  //split text into expressions and commands...
  while (listnode)
  {
    if (DEBUG)
    {
      Serial.print(listnode->text);
      Serial.print(" ");
      Serial.println(dispPrimType(listnode->type));
    }
    if (listnode->type == ID)
    {
      if (strcmp(listnode->text, "TRUE") == 0)
      {
        listnode->text = "1";
        listnode->type = NUM;
      }
      if (strcmp(listnode->text, "FALSE") == 0)
      {
        listnode->text = "0";
        listnode->type = NUM;
      }
    }
    if (tree == NIL)
    {
      current = tree = newTreeNode(listnode);
    }
    else
    {
      current = setNextNode(current, newTreeNode(listnode));
    }
    free(listnode->text);
    next = listnode->next;
    free(listnode);
    listnode = next;
  }
  return tree;
}
예제 #4
0
static TreeNode * insertIntoTree(AVLTree * tree, TreeNode * node, void * data, Boolean * success)
{
	if(node == NULL)
		return newTreeNode(data);

	int comparision = tree->compare(data, node->data);

	if(comparision == 0)
	{
		*success = false;
		return node;
	}

	int direction = comparision > 0 ? RIGHT : LEFT;

	if(direction == RIGHT)
	{
		node->right = insertIntoTree(tree, node->right, data, success);
	}
	else
	{
		node->left = insertIntoTree(tree, node->left, data, success);
	}

	updateHeight(node);

	node = balanceNode(node);

	return node;
}
// Driver program
int main()
{
    // Create root
    struct binaryTreeNode *root = newTreeNode(1);
    root->left = newTreeNode(2);
    root->right = newTreeNode(3);

    root->left->left = newTreeNode(4);
    root->left->right = newTreeNode(5);
    
    printf("Primary binary tree is: \n");
    levelOrderNonRecur(root);
    
    printf("\nlevel with max sum=%d", findLevelwithMaxSum(root));

    return 0;
}
// Driver program
int main()
{
    // Create root
    struct binaryTreeNode *root = newTreeNode(1);
    root->left = newTreeNode(2);
    root->right = newTreeNode(3);

    root->left->left = newTreeNode(4);
    root->left->right = newTreeNode(5);

    printf("Primary binary tree is: \n");
    levelOrderNonRecur(root);
	
	printf("\nThe number of full node is: \n");
	printf("%d\n", fullNodeNumberInBt(root));
	
    return 0;
}
// Driver program
int main()
{
    // Create root
    struct binaryTreeNode *root = newTreeNode(1);
    root->left = newTreeNode(2);
    root->right = newTreeNode(3);

    root->left->left = newTreeNode(4);
    root->left->right = newTreeNode(5);

    printf("Primary binary tree is: \n");
    levelOrderNonRecur(root);
	    
	printf("the deepest node is: \n");
	printf("%d", deepestNodeInBT(root)->data);
	
    return 0;
}
예제 #8
0
int main(int argc, char **argv)
{
 
    if (argc < 3) 
    {
       printf("Usage : %s <Infile> <OutFile>",argv[0]);
      return -1;
   }
    char *inname = argv[1];
    char *outname = argv[2];
    FILE *inFile,*outFile;
    char line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */
    char line_number;
    char  *tempLine;

    inFile = fopen(inname, "r");
    outFile = fopen(inname, "w");
    if (!inFile) {
        printf("Couldn't open file %s for reading.\n", inname);
        return 0;
    }
    printf("Opened file %s for reading.\n", inname);

    line_number = 0;
    tempLine=(char *)malloc(strlen("")+1);
    strcpy(tempLine,"");
    treeNode *root = newTreeNode( tempLine );
    while (fgets(line_buffer, sizeof(line_buffer), inFile)) {
        ++line_number;
        /* note that the newline is in the buffer */
        printf("%4d: %s", line_number, line_buffer);
        tempLine=(char *)malloc(strlen(line_buffer)+1);
        strcpy(tempLine,line_buffer);
        treeNode *tempNode = newTreeNode( tempLine );
        insert(&root,tempNode);
        
    }
    fclose(inFile);
    printf("\nTotal number of lines = %d\n", line_number);
    traverse(root, outFile);
    fclose(outFile);
    
    return 0;
}
예제 #9
0
struct BFTreeNode* createChild(int curPos, int toPos, int maxmin, int level, int oppCurPos) {
    struct BFTreeNode* toReturn = malloc(sizeof(struct BFTreeNode));
    struct TreeNode* createdNode = newTreeNode(graph,0,toPos-curPos,level);
    toReturn->nodeWrapped = createdNode;

    // Depends upon whether the row is a min or max row
    if (maxmin == 0) {
        toReturn->maxPos = toPos;
        toReturn->minPos = oppCurPos;
    } else {
        toReturn->minPos = toPos;
        toReturn->maxPos = oppCurPos;
    }
    return toReturn;
}
예제 #10
0
파일: tree.c 프로젝트: FooBarrior/IMCS
bool insertKeyInTree(TreePtr tree, TreeItemPtr item){
    if(NULL == tree) return false;

    assert(tree->root != NULL && item != NULL);

    if(MAX_KEY_COUNT != tree->root->keyCount)
        return insertKey(tree->root, item);

    TreeNodePtr newRoot = newTreeNode(0, NULL, false), oldRoot = tree->root;

    //newTreeNode also sets childCount to 1, so the following line fixes it
    newRoot->childCount = 0;

    oldRoot->parent = newRoot;
    tree->root = newRoot;
    addNode(newRoot, oldRoot, subforestKeyCount(oldRoot), 0);
    splitChild(newRoot, 0);
    return insertKey(tree->root, item);
}
예제 #11
0
void insertBestBST(int n, PTreeNode lastNode[])
{
    static int numNodes = 0;
    
    PTreeNode pTreeNode = newTreeNode(newNodeData(n));
    numNodes++;
    
    int level = getNodeLevel(numNodes);
    
    if (level > 0) {
        pTreeNode->left = lastNode[level - 1];
    }
    
    if (lastNode[level + 1] != NULL && lastNode[level + 1]->right == NULL) {
        lastNode[level + 1]->right = pTreeNode;
    }
    
    lastNode[level] = pTreeNode;
}
예제 #12
0
파일: tree.c 프로젝트: FooBarrior/IMCS
bool splitChild(TreeNodePtr node, int x){
    assert(node != NULL && MAX_KEY_COUNT != node->keyCount);
    assert(x >= 0 && x <= node->keyCount && node->keyCount >= 0);

    TreeNodePtr child = node->nodes[x];
    assert(child != NULL);

    TreeNodePtr newNode = newTreeNode(0, node, isLeaf(child));
    if(NULL == newNode) return false;
    newNode->childCount = 0;

    pourElements(newNode, child, t);
    //insert mediane key in node
    addKey(node, x, child->items[t - 1]);
    child->items[t - 1] = NULL;
    addNode(node, newNode, subforestKeyCount(newNode), x + 1);
    node->subtreeKeyCount[x] -= node->subtreeKeyCount[x + 1] + 1;

    return true;
}
예제 #13
0
int main(int argc, char *argv[])
{
    char word[MAX_WORD_SIZE];
    FILE *in = fopen("words.in", "r");
    BinaryTree bst;
    bst.pRoot = NULL;

    while (fscanf(in, "%s", word) == 1) {
        if (bst.pRoot == NULL) {
            bst.pRoot = newTreeNode(newNodeData(word));
        } else {
            findOrInsert(bst, newNodeData(word));
        }
    }

    printf("\nThe in-order traversal is:");
    inOrder(bst.pRoot);
    printf("\n\n");
    printf("\nThe pre-order traversal is:");
    preOrder(bst.pRoot);
    printf("\n\n");
    fclose(in);

    



    /*
    FILE *in = fopen("btree.in", "r");
    BinaryTree bt;
    bt.pRoot = buildTree(in);
    printf("\nThe in-order traversal is: ");
    preOrder(bt.pRoot);
    printf("\n\n");
    fclose(in);
    */

    return 0;
}
예제 #14
0
파일: tree.c 프로젝트: FooBarrior/IMCS
LSQ_HandleT LSQ_CreateSequence(){
    TreePtr tree = malloc(sizeof(Tree));
    tree->size = 0;
    tree->root = newTreeNode(0, NULL, true);
    return (LSQ_HandleT)tree;
}
예제 #15
0
파일: tree.c 프로젝트: LongHorn-C/Study
TreeNode * tree_append_child(TreeNode *l,PData aItem){
	//TreeNode * x=(TreeNode *)malloc(sizeof(TreeNode));
	TreeNode * x = newTreeNode();
	x->data = aItem;
	return _append_child(l,x);
}
예제 #16
0
파일: tree.c 프로젝트: LongHorn-C/Study
TreeNode * tree_prepend_child(TreeNode *l,PData aItem){
	TreeNode * x= newTreeNode();
	x->data = aItem;
	return _prepend_child(l,x);
}
예제 #17
0
// Decomposes and assigns subtrees to the various processes
// Stores the pointers to the subtree roots in temp_array
void createGameTreeParallel(struct Graph* currentState, int depth, int procs, struct BFTreeNode** temp_array) {
    struct QuoriQueue* queue;

    struct TreeNode* root = newTreeNode(currentState,0,NULL,0);
    queue = createQueue();

    // Initialize the root of the tree
    struct BFTreeNode* BFroot = (struct BFTreeNode*) malloc(sizeof(struct BFTreeNode));
    BFroot->nodeWrapped = root;
    BFroot->maxPos = (int)sqrt(NUM_NODES)/2 + 1;
    BFroot->minPos = (NUM_NODES) - (int)sqrt(NUM_NODES)/2;

    game_tree_root = BFroot;

    int currentLevel = 0, total = 0, procs_assigned = 0;

    enQueue(queue,BFroot);

    struct BFTreeNode* current;
    int position = 0, opp = 0;
    int maxmin = 0; //MAX is 0 MIN is 1

    // Building the small part of the tree that is built by every process to reference
    while (total < procs) {
        current = deQueue(queue);
        currentLevel = current->nodeWrapped->level;
        if (currentLevel%2 == 0) {
          position = current->maxPos;
          opp = current->minPos;
          maxmin = 0;
        } else {
          position = current->minPos;
          opp = current->maxPos;
          maxmin = 1;
        }

        struct BFTreeNode* newChild;

	// Use the same functions as in the serial version, using a BFS

        if (isValidMove(position,position+1)) {
            newChild = createChild(position,position+1,maxmin,currentLevel+1,opp);
            enQueue(queue,newChild);
            enQueue(current->nodeWrapped->children,newChild);
            total += 1;
        }

        if (isValidMove(position,position-1)) {
            newChild = createChild(position,position-1,maxmin,currentLevel+1,opp);
            enQueue(queue,newChild);
            enQueue(current->nodeWrapped->children,newChild);
            total += 1;
        }

        if (isValidMove(position,position+(int) sqrt(NUM_NODES))) {
            newChild = createChild(position,position+(int) sqrt(NUM_NODES),maxmin,currentLevel+1,opp);
            enQueue(queue,newChild);
            enQueue(current->nodeWrapped->children,newChild);
            total += 1;
        }

        if (isValidMove(position,position-(int) sqrt(NUM_NODES))) {
            newChild = createChild(position,position-(int) sqrt(NUM_NODES),maxmin,currentLevel+1,opp);
            enQueue(queue,newChild);
            enQueue(current->nodeWrapped->children,newChild);
            total += 1;
        }
        total -= 1;


    }

    // Assign the subtree roots to each process
    while (procs_assigned < procs - 1) {
        temp_array[procs_assigned] = deQueue(queue);
        procs_assigned++;
    }

    // Handle the special case where some process needs to hold mutiple subtrees (because the root is in the universal space)
    if (rank == procs-1) {
        struct BFTreeNode* node;
        int x = 0;
        while (queue->length > 0) {
            node = deQueue(queue);
            //printf("Node = level %d, from %d, move %d, num children %d, pid %d \n",node->nodeWrapped->level,node->minPos,node->maxPos,node->nodeWrapped->children->length,rank);

            node = createGameTree(node,depth,node->nodeWrapped->level%2);
            temp_array[rank+x] = node;
            x++;
        }
        if (x < 3) {
          for (x = x; x < 3; x++) {
            temp_array[rank+x] = NULL;
          }
        }

    } else {
        temp_array[rank] = createGameTree(temp_array[rank],depth,temp_array[rank]->nodeWrapped->level%2);
    }

    free(queue);
}
예제 #18
0
TNODE *makeParseTree(TNODE *tree)
{
	//set parent and child nodes...
	short priority, nodePriority;
	TNODE *current = NULL;
	TNODE *opcmd = NULL;
	TNODE *left = NULL;
	TNODE *right = NULL;
	TNODE *listCurrent = NULL;
	int listCount;
	//handle lists first
	current = tree;
	while (current)
	{
		//any list beginnings?
		if (current->ntype == NT_LIST_START)
		{
			listCurrent = current;
			listCount = 0;
			while (listCurrent)
			{
				switch (listCurrent->ntype)
				{
					case NT_LIST_START:
						listCount++;
						break;
					case NT_LIST_END:
						listCount--;
						if (listCount == 0)
						{
							//end of list reached...
							left = current->next; //1st expression in list
							right = listCurrent; //list end
							makeExpNode(current, left, right); //make everything in list the left child of list start, right child is list end
							left->prev = NULL; //1st expression in list has no prior nodes
							if (right->next != NULL)
								right->next->prev = current;
							current->next = right->next; //list points to node after end of the list
							right->prev->next = NULL; //the "next" of the last element in list should point to nothing
							right->prev = NULL; //the list end should point to nothing
							right->next = NULL; //the list end should point to nothing
							left = makeParseTree(left); //inner list is its own tree, parse it
							if (current->left != left)
								current->left = left; //fix tree if root changed
						}
						break;
					default:
						break;
				}
				listCurrent = listCurrent->next;
			}
		}
		current = current->next;
	}
	
	//handle nodes from highest priority to lowest
	for (priority = INFIX_PRIORITY + 4; priority >= 0; priority--)
	{
		current = tree;
		while (current)
		{
			nodePriority = (current->primIdx != -1 ? prims[current->primIdx].priority : 0);
			if (nodePriority == priority)
			{
				switch (current->ntype)
				{
					case NT_OP:
						//swap 1st and 2nd to make the op the current
						opcmd = current;
						//"numargs" not stored in nodes anymore, now comes from primitives array
						//if (opcmd->numargs != 1) // (don't swap if op is is a "NOT")
						if (prims[opcmd->primIdx].numargs != 1) // (don't swap if op is is a "NOT")
						{
							left = current->prev;
							opcmd->prev = left->prev;
							if (opcmd->prev != NULL)
								opcmd->prev->next = opcmd;
							left->next = opcmd->next;
							if (left->next != NULL)
								left->next->prev = left;
							opcmd->next = left;
							left->prev = opcmd;
							if (left == tree)
								tree = opcmd; //fix tree if first node was left
						}
						/* no break */
					case NT_CONTROL:
						opcmd = current;
						left = current->next;
						right = (current->next != NULL ? current->next->next : NULL);
						if (prims[opcmd->primIdx].numargs == 1)
						{
							/* unexpected missing argument, create one */
							if (left == NULL)
							{
								TEXTNODE *tmp = getNewTextNode("0");
								tmp->type = NUM;
								left = newTreeNode(tmp);
								free(tmp);
							}
							makeExpNode(opcmd, left, NULL);
							opcmd->next = left->next;
							if (opcmd->next != NULL)
								opcmd->next->prev = opcmd;
							left->prev = NULL;
							left->next = NULL;
						}
						else if (prims[opcmd->primIdx].numargs == 2)
						{
							makeExpNode(opcmd, left, right);
							if (left != NULL)
							{
								left->prev = NULL;
								//don't do this if type == NT_OP...
								//still buggy, EQ...
								//if (opcmd->ntype == NT_CONTROL)
									left->next = NULL;
							}
							if (right != NULL)
							{
								opcmd->next = right->next;
								if (opcmd->next)
									opcmd->next->prev = opcmd;
								right->prev = NULL;
								right->next = NULL;
							}
							else
							{
								opcmd->next = NULL;
							}
						}
						break;
					case NT_NUM:
					case NT_VAR:

						break;
					default:
						break;
				}
			}
			current = current->next;
		}
	}
	return tree;
}
// Driver program
int main()
{
    // Create root
    struct binaryTreeNode *root = newTreeNode(1);
    root->left = newTreeNode(2);
    root->right = newTreeNode(3);

    root->left->left = newTreeNode(4);
    root->left->right = newTreeNode(5);

    root->right->left = newTreeNode(6);
    
    struct binaryTreeNode *root1 = newTreeNode(1);
    root1->left = newTreeNode(2);
    root1->right = newTreeNode(3);

    root1->left->left = newTreeNode(4);
    root1->left->right = newTreeNode(5);

    root1->right->left = newTreeNode(6);
    
    printf("Primary binary tree is: \n");
    levelOrderNonRecur(root);
    levelOrderNonRecur(root1);
    
    printf("\n%d", sameStructBt(root, root1));
	
    return 0;
}