1. 程式人生 > >二叉排序樹(二叉搜尋樹)

二叉排序樹(二叉搜尋樹)

題目大意:現在給你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;
}