Background
Special for beginners, ^_^
Description
树的凹入表示法主要用于树的屏幕或打印输出,其表示的基本思想是兄弟间等长,一个结点的长度要不小于其子结点的长度。二叉树也可以这样表示,假设叶结点的长度为1,一个非叶结点的长度等于它的左右子树的长度之和。
一棵二叉树的一个结点用一个字母表示(无重复),输出时从根结点开始:
每行输出若干个结点字符(相同字符的个数等于该结点长度),
如果该结点有左子树就递归输出左子树;
如果该结点有右子树就递归输出右子树。
假定一棵二叉树一个结点用一个字符描述,现在给出先序和中序遍历的字符串,用树的凹入表示法输出该二叉树。
Format
Input
输入共两行,每行是由字母组成的字符串(一行的每个字符都是唯一的),分别表示二叉树的先序遍历和中序遍历的序列。字符串长度小于50。
Output
输出的行数等于该树的结点数,每行的字母相同。
Samples
样例输入
ABCDEFG
CBDAFEG
样例输出
AAAA
BB
C
D
EE
F
G
#include <iostream>
#include <cstring>
using namespace std;
#define MaxSize 100
struct TreeNode
{
char val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode *createNode(char val)
{
struct TreeNode *newNode = (struct TreeNode *)malloc(sizeof(struct TreeNode));
newNode->val = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int search(char arr[], int start, int end, char value)
{
for (int i = start; i <= end; i++)
{
if (arr[i] == value)
return i;
}
return -1;
}
struct TreeNode *buildTree(char preorder[], char inorder[], int inStart, int inEnd, int *preIndex)
{
if (inStart > inEnd)
return NULL;
struct TreeNode *newNode = createNode(preorder[*preIndex]);
(*preIndex)++;
if (inStart == inEnd)
return newNode;
int inIndex = search(inorder, inStart, inEnd, newNode->val);
newNode->left = buildTree(preorder, inorder, inStart, inIndex - 1, preIndex);
newNode->right = buildTree(preorder, inorder, inIndex + 1, inEnd, preIndex);
return newNode;
}
int FindLeaves(struct TreeNode *root)
{
if (root == NULL)
{
return 0;
}
if (root->left == NULL && root->right == NULL)
{
return 1;
}
int count = 0;
count += FindLeaves(root->left);
count += FindLeaves(root->right);
return count;
}
void PreOrder(struct TreeNode *root)
{
if (root != NULL)
{
for (int i = 0; i < FindLeaves(root); i++)
{
cout << root->val;
}
cout << endl;
PreOrder(root->left);
PreOrder(root->right);
}
}
int main()
{
int n;
char inorder[MaxSize];
char levelorder[MaxSize];
cin.getline(inorder, MaxSize);
cin.getline(levelorder, MaxSize);
n = strlen(inorder);
int preIndex = 0;
struct TreeNode *root = buildTree(inorder, levelorder, 0, n - 1, &preIndex);
PreOrder(root);
return 0;
}