// ConsoleApplication1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <stdlib.h> typedef struct node { char data; struct node *lchild, *rchild; } BinTreeNode; BinTreeNode *createBinTreeByGLists(char *glists, int nodeQuantity); void preOrderTraverse(BinTreeNode *node); void inOrderTraverse(BinTreeNode *node); void postOrderTraverse(BinTreeNode *node); int main(int argc, const char *argv[]) { char *gLists = "(A (B (C, D), E (, F)) )"; BinTreeNode *rootNode = createBinTreeByGLists(gLists, 6); printf("pre order:"); preOrderTraverse(rootNode); printf("\n in order:"); inOrderTraverse(rootNode); printf("\n post order:"); postOrderTraverse(rootNode); } BinTreeNode *createBinTreeByGLists(char *glists, int nodeQuantity) { BinTreeNode *rootNode = NULL; BinTreeNode *currNode = NULL; BinTreeNode **stack = (BinTreeNode **)malloc(sizeof(BinTreeNode *) * nodeQuantity); int top = -1; int flag = 0; const int START_LEFT_CHILD = 1, START_RIGHT_CHILD = 2; int index = 0; char c = glists[index]; while (c != ‘\0‘) { switch (c) { case ‘(‘: stack[++top] = currNode; flag = START_LEFT_CHILD; break; case ‘,‘: flag = START_RIGHT_CHILD; break; case ‘)‘: top--; break; case ‘ ‘: break; default: currNode = (BinTreeNode *)malloc(sizeof(BinTreeNode)); currNode->data = c; currNode->lchild = currNode->rchild = NULL; if (rootNode == NULL) { rootNode = currNode; } else { switch (flag) { case START_LEFT_CHILD: stack[top]->lchild = currNode; break; case START_RIGHT_CHILD: stack[top]->rchild = currNode; break; } } } c = glists[++index]; } free(stack); return rootNode; } void preOrderTraverse(BinTreeNode *node) { if (node != NULL) { printf("%c", node->data); preOrderTraverse(node->lchild); preOrderTraverse(node->rchild); } } void inOrderTraverse(BinTreeNode *node) { if (node != NULL) { inOrderTraverse(node->lchild); printf("%c", node->data); inOrderTraverse(node->rchild); } } void postOrderTraverse(BinTreeNode *node) { if (node != NULL) { postOrderTraverse(node->lchild); postOrderTraverse(node->rchild); printf("%c", node->data); } }