【发布时间】:2021-03-31 06:53:30
【问题描述】:
我在 C 中构建树时遇到问题。我尝试使用堆栈来处理嵌套括号,但我构建的树是错误的。我发现堆栈pionter有问题,太难了,我无法修复错误。
树是这样构建的:
#include <stdio.h>
#include<iostream>
#define MaxSize 30
using namespace std;
typedef char ElemType;
typedef struct Tnodes
{
ElemType data;
struct Tnodes* FirstChild;
struct Tnodes* NextSibling;
} TNode;
void CreateTree(TNode*& Family, char* str)
{
TNode* St[MaxSize], * p = NULL;
int top = -1;
bool k = true; //if FirstChild or NextSibling
Family = NULL;
int j = 0;
char ch = *(str + j);
while (ch != '\0')
{
switch (ch)
{
case '(':top++; St[top] = p; k = true; break; //if FirstChild,k=true
case ')':top--; break;
case ',':k = false; St[top] = p; break; //NextSibling ,k=false
default:
p = (TNode*)malloc(sizeof(TNode)); //pcreat a new node p
p->data = ch; p->FirstChild = p->NextSibling = NULL;
if (Family == NULL)
Family = p; //run for the first node
else if (k)
St[top]->FirstChild = p;
else if (!k)
St[top]->NextSibling = p;
}
j++;
ch = str[j];
}
}
//print the tree
void print_family(TNode* b, int i) {
int cnt;
if (b) {
for (cnt = 1; cnt < i; cnt++)
cout << " ";
cout << b->data << endl;
print_family(b->FirstChild, i + 1);
print_family(b->NextSibling, i);
}
}
int main()
{
char s[] = "a(b(d,e),c(g(s),f))";
TNode* Family;
CreateTree(Family, s);
print_family(Family, 5);
}
【问题讨论】:
标签: c data-structures tree