因为二叉搜索树每次插入的时候都是插入到树的最低端。
所以第一层叶子就是二叉搜索树最后一次插入的内容,第二层叶子是倒数第二次插入的内容.....
所以只需要把输入的内容倒过来建树就行了。
代码如下:
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
//节点类
struct Node
{
char c;
Node *lchild, *rchild;
Node()
{
lchild = rchild = NULL;
}
};
/**************************************************
功能: 在根节点指针为root的二叉搜索树中插入ch,
并返回插入后根节点的指针。
***************************************************/
Node* Insert(Node* root, char ch)
{
if (root == NULL)
{
Node* t = new Node();
t->c = ch;
return t;
}
else
{
if (ch < root->c)
root->lchild = Insert(root->lchild, ch);
else root->rchild = Insert(root->rchild, ch);
return root;
}
}
/*******************************************
功能: 前序遍历根节点指针为root的这棵树
********************************************/
void preorder(Node* root)
{
printf("%c", root->c);
if (root->lchild)
preorder(root->lchild);
if (root->rchild)
preorder(root->rchild);
}
int main()
{
//freopen("1.txt", "r", stdin);
int over = 0;
while (1)
{
string s;
while (1)
{
string t;
cin >> t;
if (t == "*")
break;
else if (t == "$")
{
over = 1;
break;
}
s += t;
}
int len = s.length();
Node* root = NULL;
for (int i = len - 1; i >= 0; i--)
root = Insert(root, s[i]);
preorder(root);
printf("\n");
if (over)
break;
}
return 0;
}
.