您的解析树应如下所示:
'-'
|
+---+---+
| |
'+' '4'
|
+---+---+
| |
'1' '3'
每个节点有两个指针。一个给它的左孩子,一个给它的右孩子。当使用递归遍历时,不需要指向父节点的指针。
这是一些伪代码:
中缀符号的遍历:
void traverse(Node *node) {
if (node->leftChild != 0) {
traverse(node->leftChild);
}
print(node->value);
if (node->rightChild != 0) {
traverse(node->rightChild);
}
}
前缀符号的遍历:
void traverse(Node *node) {
print(node->value);
if (node->leftChild != 0) {
traverse(node->leftChild);
}
if (node->rightChild != 0) {
traverse(node->rightChild);
}
}
后缀符号的遍历:
void traverse(Node *node) {
if (node->leftChild != 0) {
traverse(node->leftChild);
}
if (node->rightChild != 0) {
traverse(node->rightChild);
}
print(node->value);
}
You would call the traverse
method with the root node of your tree.
Your Node
data structure would need three members:
struct Node {
char value;
Node *leftChild;
Node *rightChild;
}
The leaves of the tree would contain null pointers for leftChild
and rightChild
.
Sometimes it helps to write this stuff in a higher level language (whatever you feel comfortable with) to understand the problem and then "translate" this code to assembler. I remember programming a blocks world simulation in MIPS assembler like this.