题解 | #二叉排序树#

二叉排序树

https://www.nowcoder.com/practice/b42cfd38923c4b72bde19b795e78bcb3

#include <cstdio>
#include <iostream>

using namespace std;


struct TreeNode{
    int data;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):data(x),left(NULL),right(NULL){}
};

TreeNode* Insert(TreeNode* root,int x){
    if(root==NULL){
        root = new TreeNode(x);
    }else if(x<root->data){
        root->left= Insert(root->left,x);
    }else if(x>root->data){
        root->right=Insert(root->right,x);
    }
    return root;
}

void PreOrder(TreeNode* T){
    if(T==NULL){
        return;
    }
    printf("%d ",T->data);
    PreOrder(T->left);
    PreOrder(T->right);

    return;
}
void InOrder(TreeNode* T){
    if(T==NULL){
        return;
    }
    InOrder(T->left);
    printf("%d ",T->data);
    InOrder(T->right);

    return;
}

void PostOrder(TreeNode* T){
    if(T==NULL){
        return;
    }
    PostOrder(T->left);
    PostOrder(T->right);
    printf("%d ",T->data);

    return;
}

int main(){
    int sample;
    while(scanf("%d",&sample)!=EOF){
        TreeNode* T=NULL;
        for(int i=0;i<sample;i++){
            int x;
            scanf("%d",&x);
            T=Insert(T,x);
        }

        PreOrder(T);
        printf("\n");
        InOrder(T);
        printf("\n");
        PostOrder(T);
        printf("\n");
    }
    return 0;
}

全部评论

相关推荐

10-10 16:30
济宁学院 Java
一表renzha:面试官:蓝桥杯三等奖?你多去两次厕所都能拿二等吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务