题解 | #二叉排序树#

二叉排序树

https://www.nowcoder.com/practice/30a0153649304645935c949df7599602

#include <iostream>
using namespace std;
struct TreeNode{
    int data;
    TreeNode* leftChild;
    TreeNode* rightChild;
};
TreeNode* func(TreeNode* root,int x,int father){
    if(root==NULL){
        root=(TreeNode*)malloc(sizeof(TreeNode));
        root->data=x;
        printf("%d\n",father);
    }
    else if(x<root->data) root->leftChild=func(root->leftChild,x,root->data);
    else root->rightChild=func(root->rightChild,x,root->data);
    return root;
}
int main(){
    int n,x;
    while(scanf("%d",&n)!=EOF){
        TreeNode* root=NULL;
        for(int i=0;i<n;i++){
            cin>>x;
            root=func(root,x,-1);
        }
    }
    return 0;
}

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务