码迷,mamicode.com
首页 > 编程语言 > 详细

二叉排序树

时间:2019-04-30 09:17:31      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:div   names   mes   using   style   bsp   struct   scan   clu   

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct BSTNode{
    int val;
    BSTNode* left;
    BSTNode* right;
    BSTNode* parent;
};
bool insert(BSTNode* &root, BSTNode* node){
    BSTNode* t = root;
    BSTNode* temp = NULL;
    while(t!=NULL){
        temp = t;
        if(node->val<t->val){
            t =  t->left;
        }else if(node->val>t->val){
            t = t->right;
        }else{         
            return false; 
        }
    }
    node->parent = temp;
    if (temp == NULL){
        root = node;
    }else if(node->val < temp->val){
        temp->left = node;
    }else if(node->val > temp->val){
        temp->right = node;
    }else{
        return false;
    }
    return true;
}
void preOrder(BSTNode* root){
    if (root != NULL){
        cout<<root->val<<" ";
        preOrder(root->left);
        preOrder(root->right);
    }
}
void inOrder(BSTNode* root){
    if (root != NULL){
        inOrder(root->left);
        cout<<root->val<<" ";
        inOrder(root->right);
    }
}
void postOrder(BSTNode* root){
    if (root != NULL){
        postOrder(root->left);
        postOrder(root->right);
        cout <<root->val<<" ";
    }
}
int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        BSTNode* root;
        for(int i=0;i<n;i++){
            BSTNode* node = (BSTNode*)malloc(sizeof(BSTNode));
            cin>>node->val;
            node->left = NULL;
            node->right = NULL;
            node->parent = NULL;
            if(i == 0){
                root = node;
            }else{
                insert(root,node);
            }
        }
        preOrder(root);
        cout<<endl;
        inOrder(root);
        cout<<endl;
        postOrder(root);
        cout<<endl;
    }
    return 0;
}

 

二叉排序树

标签:div   names   mes   using   style   bsp   struct   scan   clu   

原文地址:https://www.cnblogs.com/fzuhyj/p/10793805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!