varnodeu.cpp
来自「经典c++程序的实现」· C++ 代码 · 共 59 行
CPP
59 行
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include "..\include\book.h"
typedef char Operator;
typedef char* Operand;
enum Nodetype {leaf, internal}; // Enumerate possible node types
class VarBinNode { // Generic node class
public:
Nodetype mytype; // Stores the type for this particular node
union {
struct { // Structure for internal node
VarBinNode* left; // Left child
VarBinNode* right; // Right child
Operator opx; // Internal node value
} intl;
Operand var; // Leaves just store a value
};
VarBinNode(const Operand& val) // Constructor: leaf
{ mytype = leaf; var = val; }
// Constructor: Internal
VarBinNode(const Operator& op, VarBinNode* l, VarBinNode* r) {
mytype = internal; intl.opx = op; intl.left = l; intl.right = r;
}
bool isLeaf() { return mytype == leaf; }
VarBinNode* leftchild() { return intl.left; }
VarBinNode* rightchild() { return intl.right; }
};
void traverse(VarBinNode* rt) { // Preorder traversal
if (rt == NULL) return;
if (rt->isLeaf()) cout << "Leaf: " << rt->var << "\n";
else {
cout << "Internal: " << rt->intl.opx << "\n";
traverse(rt->leftchild());
traverse(rt->rightchild());
}
}
int main()
{
VarBinNode* temp1;
VarBinNode* temp2;
VarBinNode* root;
char* string1 = "Hello1";
char* string2 = "Another String";
temp1 = new VarBinNode(string1);
temp2 = new VarBinNode(string2);
root = new VarBinNode('+', temp1, temp2);
traverse(root);
return(0);
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?