长沙品质企业建站服务电话,商城网站制作公司,桂林网站搭建,wordpress网址更换Description
给出一个数据序列#xff0c;建立二叉排序树#xff0c;并实现插入功能
对二叉排序树进行中序遍历#xff0c;可以得到有序的数据序列
Input
第一行输入t#xff0c;表示有t个数据序列
第二行输入n#xff0c;表示首个序列包含n个数据
第三行输入n个数据…Description
给出一个数据序列建立二叉排序树并实现插入功能
对二叉排序树进行中序遍历可以得到有序的数据序列
Input
第一行输入t表示有t个数据序列
第二行输入n表示首个序列包含n个数据
第三行输入n个数据都是自然数且互不相同数据之间用空格隔开
第四行输入m表示要插入m个数据
从第五行起输入m行每行一个要插入的数据都是自然数且和前面的数据不等
以此类推输入下一个示例
Output
第一行输出有序的数据序列对二叉排序树进行中序遍历可以得到
从第二行起输出插入第m个数据后的有序序列输出m行
以此类推输出下一个示例的结果
Sample
#0
Input
1
6
22 33 55 66 11 44
3
77
50
10Output
11 22 33 44 55 66
11 22 33 44 55 66 77
11 22 33 44 50 55 66 77
10 11 22 33 44 50 55 66 77 AC代码
#includeiostream
using namespace std;struct TreeNode
{int data;TreeNode* left, * right;TreeNode(int val) :data(val), left(nullptr), right(nullptr) {}
};TreeNode* insert(TreeNode* root, int data)
{if (!root)return new TreeNode(data);if (data root-data)root-left insert(root-left, data);else root-right insert(root-right, data);return root;
}
void inorderTraversal(TreeNode* root) {if (root) {inorderTraversal(root-left);cout root-data ;inorderTraversal(root-right);}
}int main()
{int t;cin t;while (t--) {int n, m;TreeNode* root nullptr;cin n;for (int i 0; i n; i) {int value;cin value;root insert(root, value);}inorderTraversal(root);cout endl;cin m;for (int i 0; i m; i) {int target;cin target;root insert(root, target);inorderTraversal(root);cout endl;}}
}