题目信息
排序二叉树是指左子树的所有节点的值均小于它根节点的值,右子树的所有节点的值均大于它根节点的值。
输入
输入有一行,表示若干个要排序的数,输入0时停止
输出
二叉树的凹入表示
和二叉树的中序遍历序列
测试样例
42 168 35 101 270 125 79 259 263 165 6 246 182 62 192 296 243 28 37 0
6
28
35
37
42
62
79
101
125
165
168
182
192
243
246
259
263
270
296
6 28 35 37 42 62 79 101 125 165 168 182 192 243 246 259 263 270 296
测试样例2
147 106 291 130 71 51 7 202 94 249 132 24 85 0
7
24
51
71
85
94
106
130
132
147
202
249
291
7 24 51 71 85 94 106 130 132 147 202 249 291
解答
#include<iostream>
using namespace std;
typedef struct NODE
{
int data; //数据域
NODE *Left; //左孩子
NODE *Right; //右孩子
} BSnode, *BSTree;
bool Insert(BSTree *root, int e)
{
if ((*root) == NULL)
{//该树为一棵空树,创建一个新节点作为根节点
(*root) = new BSnode;
(*root)->data = e;
(*root)->Left = NULL;
(*root)->Right = NULL;
return true;
}
else if (e == (*root)->data)
{//数值相同,则不再继续插入
return false;
}
else if (e < (*root)->data)
{
Insert(&(*root)->Left, e);
}
else
{
Insert(&(*root)->Right, e);
}
}
void printBIT(BSTree root, int x)
{
if (root != NULL)
{
printBIT(root->Left, x + 1);
for (int i = 0; i < x; i++)
cout << " ";
cout << root->data << endl;
printBIT(root->Right, x + 1);
}
}
void inorder(BSTree root)
{//二叉树的中序遍历
if (root != NULL)
{
inorder(root->Left);
cout << " " << root->data;
inorder(root->Right);
}
}
int main()
{
//freopen("/Users/zhj/Downloads/test.txt", "r", stdin);
BSTree root = NULL;
int x;
while (1)
{
cin >> x;
if (x == 0)
{
break;
}
else
{
Insert(&root, x);
}
}
printBIT(root, 0);
cout << endl;
inorder(root);
cout << endl;
return 0;
}
本题中注意的是按照输入顺序来安排排序二叉树的,既假定第一个输入的数即为根节点