-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.c
111 lines (99 loc) · 2.4 KB
/
tree.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct TreeNode
{
char *name;
int lineno;
int intValue;
char *stringValue;
struct ChildNode *children;
} TreeNode;
typedef struct ChildNode
{
TreeNode *child;
struct ChildNode *next;
} ChildNode;
TreeNode *createTreeNode(char *name)
{
if (name == NULL)
return NULL;
TreeNode *newNode = malloc(sizeof(TreeNode));
newNode->name = name;
newNode->children = NULL;
return newNode;
}
TreeNode *createTreeNodeLine(char *name, int lineno)
{
if (name == NULL)
return NULL;
TreeNode *newNode = malloc(sizeof(TreeNode));
newNode->name = name;
newNode->lineno = lineno;
newNode->children = NULL;
return newNode;
}
TreeNode *createTreeNodeInt(char *name, int line, int value)
{
if (name == NULL)
return NULL;
TreeNode *newNode = malloc(sizeof(TreeNode));
newNode->name = name;
newNode->lineno = line;
newNode->intValue = value;
newNode->children = NULL;
return newNode;
}
TreeNode *createTreeNodeString(char *name, int line, char *value)
{
if (name == NULL)
return NULL;
TreeNode *newNode = malloc(sizeof(TreeNode));
newNode->name = name;
newNode->lineno = line;
newNode->stringValue = value;
newNode->children = NULL;
return newNode;
}
void addChild(TreeNode *parent, TreeNode *child)
{
ChildNode *newChildNode = malloc(sizeof(ChildNode));
newChildNode->child = child;
newChildNode->next = NULL;
if (parent->children == NULL)
{
parent->children = newChildNode;
}
else
{
ChildNode *current = parent->children;
while (current->next != NULL)
{
current = current->next;
}
current->next = newChildNode;
}
}
void traverseTree(TreeNode *root, int depth)
{
if (root == NULL)
return;
for (int i = 0; i < depth; i++)
{
printf(" ");
}
if (root->stringValue != NULL)
printf("%s: %s\n", root->name, root->stringValue);
else if (root->intValue != 0)
printf("%s: %d\n", root->name, root->intValue);
else if (root->lineno != 0)
printf("%s (%d)\n", root->name, root->lineno);
else
printf("%s\n", root->name);
ChildNode *current = root->children;
while (current != NULL)
{
traverseTree(current->child, depth + 1);
current = current->next;
}
}