Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // test.c
- //
- //
- // Created by 6272 on 3/9/2561 BE.
- //
- #include <stdio.h>
- #include <stdlib.h>
- #define NL printf("\n")
- struct treeNode
- {
- struct treeNode *leftPtr;
- int data;
- struct treeNode *rightPtr;
- };
- typedef struct treeNode TreeNode;
- typedef TreeNode *TreeNodePtr;
- void insertNode(TreeNodePtr *root, int value)
- {
- TreeNodePtr newNode, c;
- newNode = (TreeNodePtr)malloc(sizeof(TreeNode));
- if (newNode)
- {
- newNode->data = value;
- newNode->leftPtr = NULL;
- newNode->rightPtr = NULL;
- c = *root;
- printf("DEBUG : Inserting %d\n", value);
- if (c == NULL) *root = newNode;
- else
- {
- while (c)
- {
- if (c->data >= value)
- {
- printf("DEBUG : Going Left\n");
- if (c->leftPtr == NULL)
- {
- printf("DEBUG : Assign\n");
- c->leftPtr = newNode;
- break;
- }
- else
- {
- c = c->leftPtr;
- }
- }
- else
- {
- printf("DEBUG : Going Right\n");
- if (c->rightPtr == NULL)
- {
- printf("DEBUG : Assign\n");
- c->rightPtr = newNode;
- break;
- }
- else
- {
- c = c->rightPtr;
- }
- }
- }
- }
- }
- }
- void inOrder(TreeNodePtr treePtr)
- {
- // if tree is not empty, then traverse
- if (treePtr != NULL)
- {
- inOrder(treePtr->leftPtr); //Recursion to the left
- printf("%3d", treePtr->data); //print the value
- inOrder(treePtr->rightPtr); //Recursion to the right
- } // end if
- } // end function inOrder
- void preOrder (TreeNodePtr treePtr)
- {
- if (treePtr != NULL)
- {
- printf("%3d", treePtr->data); //print the value
- preOrder(treePtr->leftPtr); //Recursion to the left
- preOrder(treePtr->rightPtr); //Recursion to the right
- } // end if
- }
- void postOrder (TreeNodePtr treePtr)
- {
- if (treePtr != NULL)
- {
- postOrder(treePtr->leftPtr); //Recursion to the left
- postOrder(treePtr->rightPtr); //Recursion to the right
- printf("%3d", treePtr->data); //print the value
- } // end if
- }
- void lab (TreeNodePtr treePtr, int a)
- {
- a++;
- if (treePtr != NULL)
- {
- lab(treePtr->rightPtr, a); //Recursion to the right
- int i;
- for(i=0; i<a; i++)
- {
- printf(" ");
- }
- printf("%3d\n", treePtr->data); //print the value
- lab(treePtr->leftPtr, a); //Recursion to the left
- } // end if
- }
- int main(int argc, const char *argv[])
- {
- int i;
- TreeNodePtr root;
- root = NULL;
- for (i=1; i<argc; i++)
- {
- insertNode(&root, atoi(argv[i]));
- }
- printf("inOrder\n");
- inOrder(root);
- NL;
- printf("preOrder\n");
- preOrder(root);
- NL;
- printf("postOrder\n");
- postOrder(root);
- NL;
- printf("lab\n");
- lab(root, -1);
- NL;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement