建立二叉树的二叉链表存储结构(NOJ理论第15题)
这道题我采用的方法是:
- 讲题目中给的( )全部转化为 # ,这样就形成了一个扩展的先序遍历序列,然后再造二叉树
- 先序遍历输出,不过得判断这个结点是不是叶子结点,如果是的话,就不用再继续进行下去了
代码实现
// 建立二叉树的二叉链表存储结构
#include <iostream>
#include <cstring>
using namespace std;
struct Node
{
char data;
Node *LChild;
Node *RChild;
};
typedef Node *BinaryTree;
void translate(const char *source, char **target)
{//讲()形式转化为纯#形式
int count = 0;
for (int i = 0; i < strlen(source); i++)
{
if (source[i] == '(' || source[i] == ',')
{
continue;
}
else if (source[i] == '#')
{
(*target)[count] = '#';
count++;
}
else if (source[i] == ')')
{
(*target)[count] = '#';
count++;
(*target)[count] = '#';
count++;
}
else
{
(*target)[count] = source[i];
count++;
}
}
(*target)[count] = '\0';
}
BinaryTree createBinaryTree(char *&t)
{//创建二叉树
if (*t == '#')
{
t++;
return nullptr;
}
BinaryTree newroot = new Node;
newroot->data = *t;
t++;
newroot->LChild = createBinaryTree(t);
newroot->RChild = createBinaryTree(t);
return newroot;
}
void printBinaryTree(BinaryTree root)
{
if (root == nullptr)
{
cout << "#";
}
else
{
cout << root->data;
if (!root->LChild && !root->RChild)
{
}
else
{
printBinaryTree(root->LChild);
printBinaryTree(root->RChild);
}
}
}
int main()
{
char *s = new char[100];
char *t = new char[100];
char *temp = t;
BinaryTree root;
cin >> s;
translate(s, &t);
root = createBinaryTree(t);
printBinaryTree(root);
}

浙公网安备 33010602011771号