-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecur_MakeBT.cpp
54 lines (54 loc) · 1.14 KB
/
Recur_MakeBT.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
// 递归调用建立二叉树
// 从先序序列中还原二叉树
struct TreeNode
{
char data;
TreeNode *leftChild;
TreeNode *rightChild;
};
TreeNode *RecursiveBuildTree(int &i, string str)
{ // 返回的是本棵子树的根结点的地址
char c = str[i];
++i;
if (c == '#')
{
return NULL; // 返回空树
}
else
{
TreeNode *pNewNode = new TreeNode;
pNewNode->data = c;
pNewNode->leftChild = RecursiveBuildTree(i, str);
pNewNode->rightChild = RecursiveBuildTree(i, str);
return pNewNode;
}
}
void InOrder(TreeNode *root)
{
if (root == NULL)
{
return;
}
else
{
InOrder(root->leftChild);
printf("%c ", root->data);
InOrder(root->rightChild);
}
}
int main()
{
// string str = "ab##cd#gf###e##";
char str[1001];
while (scanf("%s", str) != EOF)
{
int i = 0;
TreeNode *root = RecursiveBuildTree(i, str);
InOrder(root);
printf("\n");
}
}