數據結構與算法問題 二叉排序樹
阿新 • • 發佈:2017-07-22
geo post adding ng- spa main 排序樹 ack word
- 題目描寫敘述:
-
二叉排序樹,也稱為二叉查找樹。
能夠是一顆空樹。也能夠是一顆具有例如以下特性的非空二叉樹:
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;
}數據結構與算法問題 二叉排序樹
