题目(清华机试)
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
思路
按照前序遍历特点,递归建树
代码
#include<iostream>
#include<string>
using namespace std;
int i;
string str;
struct node
{
char val;
node *left, *right;
node(char c) : val(c), left(NULL), right(NULL) {}
};
node *createTree()
{
char c = str[i++];
if(c == '#') return NULL;
node *root = new node(c);
root -> left = createTree();
root -> right = createTree();
return root;
}
void inOrder(node *root)
{
if(!root) return;
inOrder(root -> left);
cout << root -> val << " ";
inOrder(root -> right);
}
int main()
{
while(cin >> str) {
i = 0;
node *root = createTree();
inOrder(root);
cout << endl;
}
return 0;
}
网友评论