题目大意:现在给你N个关键字值各不相同的节点,要求你按顺序插入一个初始为空树的二叉排序树中,每次插入后成功后,求相应的父亲节点的关键字值,如果没有父亲节点,则输出-1。
九度OJ链接:http://ac.jobdu.com/problem.php?pid=1467
分析:二叉排序树,也称为二叉查找树或二叉搜索树。可以是一颗空树,也可以是一颗具有如下特性的非空二叉树:
1. 若左子树非空,则左子树上所有节点关键字值均不大于根节点的关键字值;
2. 若右子树非空,则右子树上所有节点关键字值均不小于根节点的关键字值;
3. 左、右子树本身也是一颗二叉排序树。
本题考虑在建树的过程中找到其父节点。
C++实现:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <memory.h>
#include <string>
#include <algorithm>
#include <iomanip>
#include <map>
#include <fstream>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;
struct Node
{
int value;
Node *left;
Node *right;
Node(int val)
{
value = val;
left = NULL;
right = NULL;
}
};
bool isBinarySearchTree(vector<int> &a, int start, int end)
{
if(start >= end)
return true;
int i = start;
while(i < end)
{
if(a[i] > a[end])
break;
i ++;
}
int j = i;
while(j < end)
{
if(a[j] < a[end])
return false;
j ++;
}
return isBinarySearchTree(a, start, i-1) &&
isBinarySearchTree(a, i, end-1);
}
void buildTree(Node *root, vector<Node*> &node)
{
if(root == NULL)
return;
Node *pre = root, *p = root;
bool tag = false;
int i = 0;
while(i < node.size())
{
p = root;
while(p != NULL)
{
pre = p;
if(node[i]->value == p->value)<span style="white-space:pre"> </span>//父节点
{
tag = true;
break;
}
else if(node[i]->value < p->value)
p = p->left;
else
p = p->right;
}
if(tag)
{
tag = false;
cout<<-1<<endl;
}
else<span style="white-space:pre"> </span>//找到其在树中的位置,创建树
{
if(node[i]->value < pre->value)
pre->left = node[i];
else
pre->right = node[i];
cout<<pre->value<<endl;
}
i ++;
}
}
void input()
{
// freopen("c:/input.txt","r",stdin);
int n;
while(scanf("%d", &n) != EOF)
{
vector<Node*> node;
Node *root = NULL, *tmp;
int x;
while(n-- > 0)
{
scanf("%d", &x);
tmp = new Node(x);
node.push_back(tmp);
}
if(node.size() > 0)
root = node[0];
if(root == NULL)
printf("-1");
else
{
buildTree(root, node);
}
}
}
int main()
{
input();
return 0;
}