Tree BulidTree(char equation[])		//Builds Expression Tree
{
	Tree T[20];
	int i;
	ExpStack S;
	S=createExpStack();
	for(i=0;equation[i]!='\0';i++)
        {
                if(equation[i]!='+' && equation[i]!='-'  && equation[i]!='/'  && equation[i]!='*')
                {
                        T[i]=createTreeNode(equation[i]);
						PushIntoExpStack(T[i],S);
                }
                else if(equation[i]=='+' || equation[i]=='-'  || equation[i]=='/'  || equation[i]=='*')
                {
					T[i]=createTreeNode(equation[i]);
					T[i]->Right=Pop_ExpStack(S);
                    T[i]->Left=Pop_ExpStack(S);
					PushIntoExpStack(T[i],S);
                }
				else
				{
					T[i]=createTreeNode(equation[i]);
					PushIntoExpStack(T[i],S);
				}

        }
	printf("Expression Tree has been successfully built!!!\n"); 
	return Pop_ExpStack(S);	//returns Root of newly built Expression Tree
}
示例#2
0
bpGraph_t* bipartGraphCreate(int part1VertNum, int part2VertNum)
{
	/* TODO: Implement me! */	
	bpGraph_t *pGraph = (bpGraph_t*) safeMalloc(sizeof(bpGraph_t));
	pGraph->vertNum1 = part1VertNum;
	pGraph->vertNum2 = part2VertNum;
	pGraph->vpVertsP1 = NULL;
	pGraph->vpVertsP2 = NULL;
	int i;
	int j;
	for (i = 0; i < part1VertNum; i++) {
		if(pGraph->vpVertsP1 == NULL) {
            pGraph->vpVertsP1 = createTreeNode(i, createList());
        } else {
        	binTreeNode_t *pNewNode = createTreeNode(i, createList());
        	insertTreeNode(pGraph->vpVertsP1, pNewNode);            
        }
	}

	for (j = 0; j < part2VertNum; j++) {
		if(pGraph->vpVertsP2 == NULL) {
            pGraph->vpVertsP2 = createTreeNode(j, createList());
        } else {
        	binTreeNode_t *pNewNode = createTreeNode(j, createList());
        	insertTreeNode(pGraph->vpVertsP2, pNewNode);            
        }
	}
	return pGraph;
} /* end of bipartGraphDestroy() */
示例#3
0
int bipartGraphInsertVertex(bpGraph_t* pGraph, int vertId, int partite)
{
		/* TODO: Implement me! */
	binTreeNode_t *currentNode = NULL, *left = NULL, *right = NULL;	

	if (partite == 1) {
		if(pGraph->vpVertsP1 == NULL) {			
            pGraph->vpVertsP1 = createTreeNode(vertId, createList());
            pGraph->vertNum1 += 1;
            return NEW_VERTEX;
        } else {
        	binTreeNode_t *pNewNode = createTreeNode(vertId, createList());       	      	
        	if (insertTreeNode(pGraph->vpVertsP1, pNewNode))  {
        		pGraph->vertNum1 += 1;
        		return NEW_VERTEX;
        	}
        	return EXISTING_VERTEX;
        }
	}

	if (partite == 2) {
		if(pGraph->vpVertsP2 == NULL) {
            pGraph->vpVertsP2 = createTreeNode(vertId, createList());
            pGraph->vertNum2 += 1;
            return NEW_VERTEX;
        } else {
        	binTreeNode_t *pNewNode = createTreeNode(vertId, createList());
        	if (insertTreeNode(pGraph->vpVertsP2, pNewNode))  {
        		pGraph->vertNum2 += 1;
        		return NEW_VERTEX;
        	}         	    
        	return EXISTING_VERTEX; 
        }
	}
} /* end of bipartGraphInsertVertex() */
示例#4
0
void insertNode(Tree* tree, void* emp, void* boss){
	struct treeNode* ptr = tree->start;
	struct Node* Nodeptr = tree->start->child;
	struct treeNode* newNode;
	if(ptr->parent == NULL){
		newNode = createTreeNode();
		newNode->employee = emp;
		tree->start = newNode;
		tree->start->child = NULL;
		tree->start->parent = (struct treeNode*)malloc(sizeof(struct treeNode));
		return;
	}
	ptr = findNode(tree, boss);
	if(ptr->child == NULL){
		newNode = createTreeNode();
		newNode->employee = emp;
		ptr->child = (struct Node*)malloc(sizeof(struct Node));
		ptr->child->value = newNode;
		ptr->child->next = NULL;
		ptr->child->value->parent = findNode(tree, boss);
		ptr->child->value->child = NULL;
	}
	else{
		while(Nodeptr->next != NULL){
			Nodeptr = Nodeptr->next;
		}
		newNode = createTreeNode();
		newNode->employee = emp;
		Nodeptr->next = (struct Node*)malloc(sizeof(struct Node));
		Nodeptr->next->value = newNode;
		Nodeptr->next->value->parent = findNode(tree, boss);
		Nodeptr->next->value->child = NULL;
		Nodeptr->next->next = NULL;
	}
}
示例#5
0
// Inserts the value provided into the given tree. Should
// follow the rule that smaller values are inserted into the
// left side of the tree; all other values are inserted into the
// right side of the tree.
//
// INPUT: root - The root of a tree to insert into, or
//               NULL if no tree yet exists.
//        data - The data to be inserted into the tree.
//
// OUTPUT: Returns the root of a tree containing the
//         newly inserted value.
Tree* insertToTree(Tree* root, int data)
{
    if(root == NULL)
    {
        return createTreeNode(data);
    }
    else
    {
        if(data < root->data)
        {
            if(root->left == NULL)
            {
                root->left = createTreeNode(data);
            }
            else
            {
                insertToTree(root->left,data);
            }
        }
        else if(data >= root->data)
        {
            if(root->right == NULL)
            {
                root->right = createTreeNode(data);
            }
            else
            {
                insertToTree(root->right,data);
            }
        }
        return root;
    }
}
示例#6
0
int bipartGraphInsertVertex(bpGraph_t* pGraph, int vertId, int partite)
{
   char **vertExists;
   binTreeNode_t **adjTree;
   int *numVerts, i;

   if (partite == 1)
   {
      vertExists = &pGraph->vertExistsP1;
      adjTree = &pGraph->adjTreeP1;
      numVerts = &pGraph->numVertsP1;
   }
   else if (partite == 2)
   {
      vertExists = &pGraph->vertExistsP2;
      adjTree = &pGraph->adjTreeP2;
      numVerts = &pGraph->numVertsP2;
   }
   else
   {
      return ERROR_VALUE;
   }

   if (vertId >= *numVerts)
   {
      /* need to expand exists array */
      *vertExists = safeRealloc(*vertExists, vertId + 1, (vertId + 1) - *numVerts);
      for (i = *numVerts; i < vertId; i++)
      {
         (*vertExists)[i] = 0;
      }
      *numVerts = vertId + 1;
   }
   else if ((*vertExists)[vertId])
   {
      return EXISTING_VERTEX;
   }

   if (*adjTree == NULL)
   {
      /* create tree */
      *adjTree = createTreeNode(vertId, createList());
   }
   else
   {
      /* or insert a node */
      insertTreeNode(*adjTree, createTreeNode(vertId, createList()));
   }
   /* set exists flag  */
   (*vertExists)[vertId] = 1;

   return NEW_VERTEX;
} /* end of bipartGraphInsertVertex() */
示例#7
0
int bipartGraphInsertVertex(bpGraph_t* pGraph, int vertId, int partite)
{
    int status;
    binTreeNode_t *vertex;

	if(partite==1){
        vertex=searchValue(*pGraph->vertices1, vertId);

        /* Check if vertex already exists */
        if(vertex==NULL){

            if(*pGraph->vertices1==NULL){
                *pGraph->vertices1 = createTreeNode(vertId, NULL);

                return NEW_VERTEX;
            }
            else{
                /* initialise new node */
                binTreeNode_t *newNode = createTreeNode(vertId, NULL);

                status = insertTreeNode(*pGraph->vertices1,newNode);

                return status;
            }
        }

        return EXISTING_VERTEX;
	}else if(partite==2){
        vertex=searchValue(*pGraph->vertices2, vertId);

        /* Check if vertex already exists */
        if(vertex==NULL){

            if(*pGraph->vertices2==NULL){
                *pGraph->vertices2 = createTreeNode(vertId, NULL);

                return NEW_VERTEX;
            }
            else{
                /* initialise new node */
                binTreeNode_t *newNode = createTreeNode(vertId, NULL);

                status = insertTreeNode(*pGraph->vertices2,newNode);

                return status;
            }
        }

        return EXISTING_VERTEX;
	}

	return ERROR_VALUE;
} /* end of bipartGraphInsertVertex() */
示例#8
0
int main()
{
	TreeNode *p = createTreeNode(0);
	strcpy(p->symbol, "TYPE");
	strcpy(p->text, "int");
	TreeNode *q = createTreeNode(0);
	strcpy(q->symbol, "INT");
	q->intVal = 15;
	TreeNode *r = createTreeNode(2, p, q);
	printTree(r, 0);
	deleteTree(r);
	return 0;
}
示例#9
0
/*
 * Function used to create a balanced tree
 * during the create BP graph function
 */
void createBalancedTree(binTreeNode_t ** pTree, int parentValue, int maxValue)
{
    int numToCreate = 0;
    binTreeNode_t * tempNode = NULL;

    /* get the middle number and divide by two*/
    numToCreate = (maxValue - parentValue) / 2;
    numToCreate = numToCreate + parentValue;
    /* round up to the nearest whole number */
    if((maxValue - parentValue) % 2 == 1)
    {
        numToCreate++;
    }
    /* create the node */
    tempNode = createTreeNode(numToCreate, NULL);
    *pTree = tempNode;

    if(parentValue < numToCreate)
    {
        /* create left node */
        createBalancedTree(&tempNode->left, parentValue, numToCreate - 1);
    }
    if(maxValue > numToCreate)
    {
        /*create right node */
        createBalancedTree(&tempNode->right, numToCreate+1, maxValue);
    }
}
示例#10
0
文件: tree.c 项目: aniketsr/DSA
int insertIntoTree(Tree* tree, void* parentData, void* childData){
	TreeNode *root = (TreeNode*)tree->root;
	TreeNode *nodeToInsert, *parentNode;
	if(NULL == tree->root){
		tree->root = createTreeNode(childData, NULL);
		return 1;
	}
	if(0 == tree->cmp(root->data,parentData)){
		parentNode = root;
		nodeToInsert = createTreeNode(childData, parentNode);
		insert(&root->children, 0, nodeToInsert);
		return 1;
	}
	parentNode = getTreeNode(root->children, parentData, tree->cmp);
	nodeToInsert = createTreeNode(childData, parentNode);
	insert(&parentNode->children, 0, nodeToInsert);
	return 1;
}
示例#11
0
// use the current element,parent point and whether the current node is leftChild or rightChild to add a new node.
void addTreeNode(ElementType element,TreeNode* parent,char mark){
    TreeNode* child = createTreeNode(element);
    switch(mark){
        case 'L':
            parent->lc = child;
            break;
        case 'R':
            parent->rc = child;
            break;
        }
}
示例#12
0
文件: 4-3.c 项目: gsrr/Programs
void createBSTByOrder(int* arr, int num)
{
        tNode* root = createTreeNode(&arr[0]);
        int i;
        for( i = 1 ; i < num ; i++)
        {
                appendBST(&root, arr, i, i);
        }
        printf("\nheight:%d\n", treeHeight(root));
        print_tree(root, print);
}
示例#13
0
文件: 4-7.c 项目: gsrr/Programs
tNode* createBSTRoot(int* arr, int num)
{
        int low = 0;
        int high = num - 1;
        int middle = (low + high)/2;

        tNode* root = createTreeNode(&arr[middle]);
        appendBST(&root, arr, low, middle-1);
        appendBST(&root, arr, middle+1, high);
        return root;
}
示例#14
0
binTreeNode_t *createAdjTree(int start, int end)
{
   binTreeNode_t *tree;
   int pivot;

   if (end - start == 0)
   {
      return NULL;
   }
   else if (end - start == 1)
   {
      return createTreeNode(start, createList());
   }

   pivot = (start + end) / 2;
   tree = createTreeNode(pivot, createList());
   tree->left = createAdjTree(start, pivot);
   tree->right = createAdjTree(pivot + 1, end);

   return tree;
}
示例#15
0
文件: 4-3.c 项目: gsrr/Programs
void createLTreeByArr(tNode** root, int* arr, int low, int high)
{
        if(high < low)
        {
                return;
        }
        int middle = (low + high)/2;
        tNode* tmp = createTreeNode(&arr[middle]);
        (*root)->lchild = tmp;
        createLTreeByArr(&((*root)->lchild), arr, low, middle - 1);
        createRTreeByArr(&((*root)->lchild), arr, middle + 1, high);
}
void solveTreeNode()
{
    //Level 0
    TreeNode* root = createTreeNode(10);
    
    //Level 1
    root->left = createTreeNode(7);
    root->right = createTreeNode(25);
    
    //Level 2
    root->left->left = createTreeNode(30);
    root->left->right = createTreeNode(10);
    root->right->left = createTreeNode(50);
    root->right->right = createTreeNode(7);
    
    //Level 3
    root->right->left->left = createTreeNode(11);
    root->right->right->left = createTreeNode(12);
    root->right->right->right = createTreeNode(35);
    
    //Find the max of all the elements in the binary tree
    printf("%d",findMaxRecur(root));
}
示例#17
0
文件: 4-3.c 项目: gsrr/Programs
void appendBST(tNode** root, int* arr, int low, int high)
{
        if(high < low)
        {
                return;
        }
        tNode* data = *root;
        int* ritem = (int*)data->item; 
        int middle = (low + high)/2;
        tNode* tmp = createTreeNode(&arr[middle]);
          
        appendData(root, tmp);
        appendBST(root, arr, low, middle-1);
        appendBST(root, arr, middle+1, high);
}
void test()
{
    TreeNode* root = NULL;
    int i = 1;
    while(1)
    {
        root=createTreeNode(1);
        if(root==NULL)
        {
            printf("MEMORY ERROR");
            break;
        }
        printf("Allocated Memory :%u\n",root);
        i++;
    }
    printf("\nTotal Chunks: %d",i);
}
示例#19
0
nodeT* createBinaryTree()
{
    nodeT* p;
    char* data = (char*)malloc(sizeof(char)*100);
    fscanf(f, "%s", data);
    if(strcmp(data, "*") == 0)
    {
        return NULL;
    }
    else
    {
        p = createTreeNode(atoi(data));
        p->left = createBinaryTree();
        p->right = createBinaryTree();
    }
    return p;
}
示例#20
0
BinaryTreeNode<Key, Value>* BinarySearchTree<Key, Value>::insertHelper(
		BinaryTreeNode<Key, Value>* subRoot, const Key& key, const Value& value)
{
	if (subRoot == NULL)
	{
		createTreeNode(key, value, subRoot);
	}
	else if (subRoot->keyEquals(key) > 0)
	{
		subRoot->setRightChild(insertHelper(subRoot->rightChild(), key, value));
	}
	else if (subRoot->keyEquals(key) <= 0)
	{
		subRoot->setLeftChild(insertHelper(subRoot->leftChild(), key, value));
	}
	return subRoot;
}
示例#21
0
文件: tree.c 项目: sumitvarude/DSA
int insertTreeNode(Tree *tree,void *parent,void *child){
	TreeNode *node = createTreeNode(child);
	TreeNode *matchedTreeNode;
	List* list;
	if(parent == NULL){
		tree->root = node;
		return 1;
	}
	matchedTreeNode =  searchTreeNode(tree,parent);
	node->parent = matchedTreeNode;
	if(matchedTreeNode->list == NULL){
		list = create();
		matchedTreeNode->list = list;
	}
	list = matchedTreeNode->list;
	insert(list,node,1);
	return 1;
};
示例#22
0
	//init-- intializes the quad tree
	//terrain- the terrain to build the quad tree from
	//device- the device to use for initialization
	bool TerrainQuadTree::init(Terrain* terrain, ID3D11Device* device)
	{
		int vertexCount;
		float centerX, centerZ, width;

		//Get the number of vertices in the terrain vertex array
		vertexCount = terrain->getVertexCount();

		//store the total triangle count for the vertex list
		m_triangleCount = vertexCount / 3;

		//create a vertex array to hold ll of the terrain vertices
		m_vertexList = new Vertex[vertexCount];
		if (!m_vertexList)
		{
			return false;
		}

		//copy the terrain vertices into the vertex list
		terrain->copyVertexArray((void*)m_vertexList);

		//Calculate the center x,z and the width of the mesh
		calculateMeshDimensions(vertexCount, centerX, centerZ, width);

		//create the parent node for the quadtree
		m_parentNode = new Node;
		if (!m_parentNode)
		{
			return false;
		}

		//recusivly build th quad tree based on the vertex list data and mesh dimensions.
		createTreeNode(m_parentNode, centerX, centerZ, width, device);

		//release the vertex list since it is needed
		if (m_vertexList)
		{
			delete[] m_vertexList;
			m_vertexList = NULL;
		}

		return true;

	}
示例#23
0
nodeT* createTreeFromList(nodeL **node)
{
    nodeT* p;

    char *c = (*node)->data;
    *node = (*node)->next;
    if(strcmp(c, "*") == 0)
    {
        return NULL;
    }
    else
    {
        p = createTreeNode(atoi(c));
        p->left = createTreeFromList(node);
        p->right = createTreeFromList(node);
    }

    return p;
}
示例#24
0
int main()
{
    ElementType curr_ele,parent_ele;
    TreeNode* root = NULL;
    char mark;
    while(1){
        scanf("%c%c%c",&curr_ele,&parent_ele,&mark);
        getchar();
        // fflush(stdout);
        // printf("%c %c %c\n",curr_ele,parent_ele,mark);
        if(curr_ele == '#'){                               // '#' is like a NULL or None.
            break;
        }else if(parent_ele == '#'){
            root = createTreeNode(curr_ele);
        }else{
            addTreeNodeByUser(root,curr_ele,parent_ele,mark);
        }
    }
    testTraverse(root);
    return 0;
}
示例#25
0
文件: 4-3.c 项目: gsrr/Programs
int main()
{
        int num = 20;
        int* arr = createArr(num);
        int low = 0 ; 
        int high = num - 1;
        int middle = (low + high)/2;
        //tNode* root = createTreeNode(&arr[middle]);
        //createLTreeByArr(&root, arr, low, middle - 1);
        //createRTreeByArr(&root, arr, middle + 1, high);
        //printf("height:%d\n", treeHeight(root));
        //print_tree(root, print);
        printf("\n");
        tNode* binRoot = createTreeNode(&arr[middle]);
        appendBST(&binRoot, arr, low, middle-1);
        appendBST(&binRoot, arr, middle+1, high);
        printf("height:%d\n", treeHeight(binRoot));
        print_tree(binRoot, print);
        //createBSTByOrder(arr, num);

        return 0;
}
示例#26
0
/* The main function that constructs balanced BST and returns root of it.
head_ref -->  Pointer to pointer to head node of linked list
n  --> No. of nodes in Linked List */
TreeNode sortedListToBSTRecur(Node *head_ref, int n)
{
	/* Base Case */
	if (n <= 0)
		return NULL;

	/* Recursively construct the left subtree */
	TreeNode left = sortedListToBSTRecur(head_ref, (int)(n / 2));

	/* Allocate memory for root, and link the above constructed left
	subtree with root */
	TreeNode root = createTreeNode((*head_ref)->data);
	root->left = left;

	/* Change head pointer of Linked List for parent recursive calls */
	*head_ref = (*head_ref)->next;

	/* Recursively construct the right subtree and link it with root
	The number of nodes in right subtree  is total nodes - nodes in
	left subtree - 1 (for root) which is n-n/2-1*/
	root->right = sortedListToBSTRecur(head_ref, n - n / 2 - 1);

	return root;
}
示例#27
0
int main(void) {

	printf("\n");
	printf("\t --TESTING TREESUPPLEMENT--\n");
	printf("\n");

	/* Testing createTreeNode */
	printf("-- CREATETREENODE\n");
	printf("Input to createTreeNode: (\"McDonalds\", \"Fast food\", 3)\n");
	void * testNode;
	testNode = createTreeNode("McDonalds", "Fast food", 3);
	printf("Output: %p - A pointer address\n", testNode);
	int x;
	int correctMembers;
	correctMembers = 0;
	char * testName = "McDonalds.";
	for (x = 0; ((restaurantTNode*)testNode)->name[x] == testName[x]; ++x);
	if (x == 9)
		++correctMembers;
	else
		printf("FAILED to copy name\n");
	char * testFType = "Fast food.";
	for (x = 0; ((restaurantTNode*)testNode)->foodType[x] == testFType[x]; ++x);
	if (x == 9)
		++correctMembers;
	else
		printf("FAILED to copy foodType\n");

	if (((restaurantTNode*)testNode)->rating == 3)
		++correctMembers;
	else
		printf("FAILED to copy rating\n");
	if (correctMembers == 3)
		printf("-- SUCCESS\n");
	else
		printf("-- FAIL\n");
	printf("\n");
	/* End of testing createTreeNode */

	/* Testing compareName */
	printf("-- COMPARENAME\n");
	int correctNums;
	correctNums = 0;
	printf("creating new tree node with createTreeNode(\"Burger King\", \"Fast food\", 4)\n");
	void * testNode2;
	testNode2 = createTreeNode("Burger King", "Fast food", 4);
	printf("Input to compareName: (%p, %p)\n", testNode, testNode2);
	printf("{First arguement is the first tree node we created (McDonalds) and second is the new one (Burger King)}\n");
	int resultOutput;
	resultOutput = compareName(testNode, testNode2);
	printf("Output:          %d\n", resultOutput);
	printf("Expected output: -1\n");
	if (resultOutput == -1)
		++correctNums;
	else
		printf("FAILED to compare names\n");
	printf("Shortening \"Burger King\" to \"Burger Ki\" (equal in length to McDonalds)\n");
	((restaurantTNode*)testNode2)->name[9] = '\0';
	printf("Reinputting the original node and the altered node\n");
	resultOutput = compareName(testNode, testNode2);
	printf("Output:          %d\n", resultOutput);
	printf("Expected output: 0\n");
	if (resultOutput == 0)
		++correctNums;
	else
		printf("FAILED to compare names\n");
	printf("Shortening \"Burger Ki\" to \"Burger\" (less than the length of McDonalds)\n");
	((restaurantTNode*)testNode2)->name[6] = '\0';
	printf("Reinputting the original node and the again altered node\n");
	resultOutput = compareName(testNode, testNode2);
	printf("Output:          %d\n", resultOutput);
	printf("Expected output: 1\n");
	if (resultOutput == 1)
		++correctNums;
	else
		printf("FAILED to compare names\n");
	if (correctNums == 3)
		printf("-- SUCCESS\n");
	else
		printf("-- FAIL\n");
	printf("\n");
	/* End of testing compareName */

	/* Testing compareRating */
	printf("-- COMPARERATING\n");
	correctNums = 0;
	printf("Input to compareRating: (%p, %p)\n", testNode, testNode2);
	printf("{First arguement is the first tree node we created, McDonalds (Rating: 3) and second is Burger King (Rating: 4)\n");
	resultOutput = compareRating(testNode, testNode2);
	printf("Output:          %d\n", resultOutput);
	printf("Expected output: -1\n");
	if (resultOutput == -1)
		++correctNums;
	else
		printf("FAILED to compare rating\n");
	printf("Changing Burger King's rating to 3\n");
	((restaurantTNode*)testNode2)->rating = 3;
	printf("Reinputting the original node and the altered node\n");
	resultOutput = compareRating(testNode, testNode2);
	printf("Output:          %d\n", resultOutput);
	printf("Expected output: 0\n");
	if (resultOutput == 0)
		++correctNums;
	else
		printf("FAILED to compare rating\n");
	printf("Changing Burger King's rating to 2\n");
	((restaurantTNode*)testNode2)->rating = 2;
	printf("Reinputting the original node and the altered node\n");
	resultOutput = compareRating(testNode, testNode2);
	printf("Output:          %d\n", resultOutput);
	printf("Expected output: 1\n");
	if (resultOutput == 1)
		++correctNums;
	else
		printf("FAILED to compare rating\n");
	if (correctNums == 3)
		printf("-- SUCCESS\n");
	else
		printf("-- FAIL\n");
	printf("\n");
	/* End of testing compareRating */

	printf("\t --END OF TESTING TREESUPPLEMENT--\n");
	printf("\n");

	return 0;
}
示例#28
0
	//createTreeNode- creates the node for the tree
	//positionX- the x position of the node
	//positionZ- the z position of the node
	//width- the width of the node
	//device- the device to use
	void TerrainQuadTree::createTreeNode(Node* node, float positionX, float positionZ, float width, ID3D11Device* device)
	{
		int numTriangles, i, count, vertexCount, index, vertexIndex;
		float offsetX, offsetZ;
		Vertex* vertices;
		unsigned long* indices;
		bool result;
		D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
		D3D11_SUBRESOURCE_DATA vertexData, indexData;

		// Store the node position and size.
		node->positionX = positionX;
		node->positionZ = positionZ;
		node->width = width;

		// Initialize the triangle count to zero for the node.
		node->triangleCount = 0;

		// Initialize the vertex and index buffer to null.
		node->vertexBuffer = 0;
		node->indexBuffer = 0;

		//init the vertex array to null

		node->vertexArray = NULL;

		// Initialize the children nodes of this node to null.
		node->nodes[0] = 0;
		node->nodes[1] = 0;
		node->nodes[2] = 0;
		node->nodes[3] = 0;

		// Count the number of triangles that are inside this node.
		numTriangles = countTriangles(positionX, positionZ, width);

		// If there are no triangles in this node then return as it is empty and requires no processing.
		if (numTriangles == 0)
		{
			return;
		}

		// If there are too many triangles in this node then split it into four equal sized smaller tree nodes.
		if (numTriangles > m_maxTriangles)
		{
			for (i = 0; i<4; i++)
			{
				// Calculate the position offsets for the new child node.
				offsetX = (((i % 2) < 1) ? -1.0f : 1.0f) * (width / 4.0f);
				offsetZ = (((i % 4) < 2) ? -1.0f : 1.0f) * (width / 4.0f);

				// See if there are any triangles in the new node.
				count = countTriangles((positionX + offsetX), (positionZ + offsetZ), (width / 2.0f));
				if (count > 0)
				{
					// If there are triangles inside where this new node would be then create the child node.
					node->nodes[i] = new Node;

					// Extend the tree starting from this new child node now.
					createTreeNode(node->nodes[i], (positionX + offsetX), (positionZ + offsetZ), (width / 2.0f), device);
				}
			}

			return;
		}

		// If this node is not empty and the triangle count for it is less than the max then 
		// this node is at the bottom of the tree so create the list of triangles to store in it.
		node->triangleCount = numTriangles;

		// Calculate the number of vertices.
		vertexCount = numTriangles * 3;

		// Create the vertex array.
		vertices = new Vertex[vertexCount];

		// Create the index array.
		indices = new unsigned long[vertexCount];

		//Create the vertex array
		node->vertexArray = new Vector[vertexCount];

		// Initialize the index for this new vertex and index array.
		index = 0;

		// Go through all the triangles in the vertex list.
		for (i = 0; i<m_triangleCount; i++)
		{
			// If the triangle is inside this node then add it to the vertex array.
			result = isTriangleContained(i, positionX, positionZ, width);
			if (result == true)
			{
				// Calculate the index into the terrain vertex list.
				vertexIndex = i * 3;

				// Get the three vertices of this triangle from the vertex list.
				vertices[index].position = m_vertexList[vertexIndex].position;
				vertices[index].texture = m_vertexList[vertexIndex].texture;
				vertices[index].normal = m_vertexList[vertexIndex].normal;
				indices[index] = index;


				// Also store the vertex position information in the node vertex array.
				node->vertexArray[index].x = m_vertexList[vertexIndex].position.x;
				node->vertexArray[index].y = m_vertexList[vertexIndex].position.y;
				node->vertexArray[index].z = m_vertexList[vertexIndex].position.z;

				// Increment the indexes.
				index++;
				vertexIndex++;

				// Do the same for the next point.
				vertices[index].position = m_vertexList[vertexIndex].position;
				vertices[index].texture = m_vertexList[vertexIndex].texture;
				vertices[index].normal = m_vertexList[vertexIndex].normal;
				indices[index] = index;
				node->vertexArray[index].x = m_vertexList[vertexIndex].position.x;
				node->vertexArray[index].y = m_vertexList[vertexIndex].position.y;
				node->vertexArray[index].z = m_vertexList[vertexIndex].position.z;
				index++;
				vertexIndex++;

				// Do the same for the next point also.
				vertices[index].position = m_vertexList[vertexIndex].position;
				vertices[index].texture = m_vertexList[vertexIndex].texture;
				vertices[index].normal = m_vertexList[vertexIndex].normal;
				indices[index] = index;
				node->vertexArray[index].x = m_vertexList[vertexIndex].position.x;
				node->vertexArray[index].y = m_vertexList[vertexIndex].position.y;
				node->vertexArray[index].z = m_vertexList[vertexIndex].position.z;
				index++;

			}
		}

		// Set up the description of the vertex buffer.
		vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
		vertexBufferDesc.ByteWidth = sizeof(Vertex) * vertexCount;
		vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		vertexBufferDesc.CPUAccessFlags = 0;
		vertexBufferDesc.MiscFlags = 0;
		vertexBufferDesc.StructureByteStride = 0;

		// Give the subresource structure a pointer to the vertex data.
		vertexData.pSysMem = vertices;
		vertexData.SysMemPitch = 0;
		vertexData.SysMemSlicePitch = 0;

		// Now finally create the vertex buffer.
		device->CreateBuffer(&vertexBufferDesc, &vertexData, &node->vertexBuffer);

		// Set up the description of the index buffer.
		indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
		indexBufferDesc.ByteWidth = sizeof(unsigned long) * vertexCount;
		indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
		indexBufferDesc.CPUAccessFlags = 0;
		indexBufferDesc.MiscFlags = 0;
		indexBufferDesc.StructureByteStride = 0;

		// Give the subresource structure a pointer to the index data.
		indexData.pSysMem = indices;
		indexData.SysMemPitch = 0;
		indexData.SysMemSlicePitch = 0;

		// Create the index buffer.
		device->CreateBuffer(&indexBufferDesc, &indexData, &node->indexBuffer);

		// Release the vertex and index arrays now that the data is stored in the buffers in the node.
		delete[] vertices;
		vertices = 0;

		delete[] indices;
		indices = 0;


	}