struct node *Create(char *str)
{
//str是二叉树的广义表表示的字符串
//st是栈空间,b是新建二叉链表的根指针
struct node *St[100],*P = NULL,*b;
int top = -1,k,j = 0;
char ch;
ch = str[j];
//初始化的二叉链为空
b = NULL;
for (j = 0; str[j] != '\0';j ++)
{
ch = str[j];
switch (ch)
{
//作为左结点
case '(':
top ++;
St[top] = P;
k =1;
break;
case ')':
top --;
break;
//作为右结点
case ',':
k = 2;
break;
default:
P = (struct node *)malloc(sizeof(struct node));
P->data = ch;
P->left = P->right = NULL;
if (b == NULL)
{
// p指向二叉树的根结点
b = P;
}
else
{
switch(k)
{
case 1:
St[top]->left= P;
break;
case 2:
St[top]->right = P;
break;
}
}
}
}
return b;
}
后续遍历(非递归)
// C program for iterative postorder traversal using one stack
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// A tree node
struct Node
{
int data;
struct Node *left, *right;
};
// Stack type
struct Stack
{
int size;
int top;
struct Node* *array;
};
// A utility function to create a stack of given size
struct Stack* createStack(int size)
{
struct Stack* stack =
(struct Stack*) malloc(sizeof(struct Stack));
stack->size = size;
stack->top = -1;
stack->array =
(struct node**) malloc(stack->size * sizeof(struct node*));
return stack;
}
// BASIC OPERATIONS OF STACK
int isFull(struct Stack* stack)
{ return stack->top - 1 == stack->size; }
int isEmpty(struct Stack* stack)
{ return stack->top == -1; }
void push(struct Stack* stack, struct node* node)
{
if (isFull(stack))
return;
stack->array[++stack->top] = node;
}
struct node* pop(struct Stack* stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top--];
}
// An iterative function to do post order traversal of a given binary tree
void postOrderIterative(struct node* root)
{
if (root == NULL)
return;
// Create two stacks
struct Stack* s1 = createStack(MAX_SIZE);
struct Stack* s2 = createStack(MAX_SIZE);
// push root to first stack
push(s1, root);
struct node* node;
// Run while first stack is not empty
while (!isEmpty(s1))
{
// Pop an item from s1 and push it to s2
node = pop(s1);
push(s2, node);
// Push left and right children of removed item to s1
if (node->left)
push(s1, node->left);
if (node->right)
push(s1, node->right);
}
// Print all elements of second stack
while (!isEmpty(s2))
{
node = pop(s2);
printf("%c", node->data);
//cout << node->data;
}
}
Construct Tree from given Inorder and Preorder traversals