時間限制:1 秒
內存限制:128 兆
特殊判題:否
提交:3883
解決:1566
- 題目描述:
-
二叉排序樹,也稱爲二叉查找樹。可以是一顆空樹,也可以是一顆具有如下特性的非空二叉樹:
1. 若左子樹非空,則左子樹上所有節點關鍵字值均不大於根節點的關鍵字值;
2. 若右子樹非空,則右子樹上所有節點關鍵字值均不小於根節點的關鍵字值;
3. 左、右子樹本身也是一顆二叉排序樹。
現在給你N個關鍵字值各不相同的節點,要求你按順序插入一個初始爲空樹的二叉排序樹中,每次插入後成功後,求相應的父親節點的關鍵字值,如果沒有父親節點,則輸出-1。
- 輸入:
-
輸入包含多組測試數據,每組測試數據兩行。
第一行,一個數字N(N<=100),表示待插入的節點數。
第二行,N個互不相同的正整數,表示要順序插入節點的關鍵字值,這些值不超過10^8。
- 輸出:
-
輸出共N行,每次插入節點後,該節點對應的父親節點的關鍵字值。
- 樣例輸入:
-
5 2 5 1 3 4
- 樣例輸出:
-
-1 2 2 5
3
-
#include<iostream> #include<vector> using namespace std; typedef struct bs { int num; struct bs* lchild; struct bs* rchild; }node; vector<int>re0; void insert(node*head,int x) { if(head) { if(x<head->num) { if(head->lchild==NULL) { re0.push_back(head->num); node*lchild=new node(); lchild->lchild=lchild->rchild=NULL; lchild->num=x; head->lchild=lchild; } else{ insert(head->lchild,x); } } else{ if(head->rchild==NULL) { re0.push_back(head->num); //cout<<head->num<<endl; node*rchild=new node(); rchild->lchild=rchild->rchild=NULL; rchild->num=x; head->rchild=rchild; } else{ insert(head->rchild,x); } } } } int main() { //head->lchild=head->rchild=NULL; int n,x; //bool first=true; while(cin>>n) {node*head=NULL; re0.clear(); while(n--) { cin>>x; if(head==NULL) { head=new node(); head->lchild=head->rchild=NULL; head->num=x; //cout<<-1<<endl; re0.push_back(-1); } else insert(head,x); } for(int i=0;i<re0.size();i++) cout<<re0[i]<<endl; } }