-
题目描写叙述:
-
二叉排序树,也称为二叉查找树。
能够是一颗空树。也能够是一颗具有例如以下特性的非空二叉树:
1. 若左子树非空,则左子树上全部节点keyword值均不大于根节点的keyword值;
2. 若右子树非空,则右子树上全部节点keyword值均不小于根节点的keyword值。
3. 左、右子树本身也是一颗二叉排序树。
如今给你N个keyword值各不同样的节点,要求你按顺序插入一个初始为空树的二叉排序树中,每次插入后成功后。求对应的父亲节点的keyword值。假设没有父亲节点,则输出-1。
-
输入:
-
输入包括多组測试数据,每组測试数据两行。
第一行,一个数字N(N<=100),表示待插入的节点数。
第二行,N个互不同样的正整数,表示要顺序插入节点的keyword值。这些值不超过10^8。
-
输出:
-
输出共N行。每次插入节点后,该节点相应的父亲节点的keyword值。
-
例子输入:
-
5 2 5 1 3 4
例子输出:
-1
2
2
5
3
#include <iostream>
using namespace std;
struct bitree
{
int data, parent_num;
bitree *lchild, *rchild;
};
void insert(bitree *root_,bitree * &root, int & data)
{
if (!root)
{
root = new bitree;
root->data = data;
root->lchild = NULL;
root->rchild = NULL;
root->parent_num =root_->data;
}
if (data > root->data)
{
insert(root, root->rchild, data);
}
if (data < root->data)
{
insert(root, root->lchild, data);
}
}
void inorder(bitree * &root)
{
if (root)
{
cout << root->parent_num << endl;
inorder(root->lchild);
inorder(root->rchild);
}
}
int main()
{
bitree *root = NULL;
int n;
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; i++)
cin >> a[i];
if (!root)
{
root = new bitree;
root->data = a[0];
root->lchild = NULL;
root->rchild = NULL;
root->parent_num = -1;
}
for (int i = 1; i < n;i++)
insert(root,root, a[i]);
inorder(root);
return 0;
}