首页 > 代码库 > 九度oj 题目1467:二叉排序树
九度oj 题目1467:二叉排序树
题目1467:二叉排序树
时间限制:1 秒
内存限制:128 兆
特殊判题:否
提交:4102
解决:1644
- 题目描述:
二叉排序树,也称为二叉查找树。可以是一颗空树,也可以是一颗具有如下特性的非空二叉树:
1. 若左子树非空,则左子树上所有节点关键字值均不大于根节点的关键字值;
2. 若右子树非空,则右子树上所有节点关键字值均不小于根节点的关键字值;
3. 左、右子树本身也是一颗二叉排序树。
现在给你N个关键字值各不相同的节点,要求你按顺序插入一个初始为空树的二叉排序树中,每次插入后成功后,求相应的父亲节点的关键字值,如果没有父亲节点,则输出-1。
- 输入:
输入包含多组测试数据,每组测试数据两行。
第一行,一个数字N(N<=100),表示待插入的节点数。
第二行,N个互不相同的正整数,表示要顺序插入节点的关键字值,这些值不超过10^8。
- 输出:
输出共N行,每次插入节点后,该节点对应的父亲节点的关键字值。
- 样例输入:
52 5 1 3 4
- 样例输出:
-12253
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 using namespace std; 5 6 typedef struct node { 7 int val; 8 struct node* left; 9 struct node* right;10 }Node;11 12 int insert(Node* &root, int val, int father) {13 if (root == NULL) {14 root = (Node*)malloc(sizeof(Node));15 root->left = NULL;16 root->right = NULL;17 root->val = val;18 return father;19 }20 if (root->val > val) {21 insert(root->left, val, root->val);22 } else if (root->val < val) {23 insert(root->right, val, root->val);24 }25 }26 27 int main(){28 int n, temp;29 while (cin >> n) {30 Node* root = NULL;31 while (n--) {32 cin >> temp;33 cout << insert(root, temp, -1) << endl;34 }35 }36 return 0;37 }
九度oj 题目1467:二叉排序树
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。