题解 | #明明的随机数#
明明的随机数
https://www.nowcoder.com/practice/3245215fffb84b7b81285493eae92ff0
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
// 插入函数
struct TreeNode* insert(struct TreeNode* node, int val) {
if (node == NULL) {
struct TreeNode* temp = (struct TreeNode*)malloc(sizeof(struct TreeNode));
temp->val = val;
temp->left = temp->right = NULL;
return temp;
}
if (val < node->val) {
node->left = insert(node->left, val);
} else if (val > node->val) {
node->right = insert(node->right, val);
}
// 如果val等于node->val,不插入(去重)
return node;
}
// 中序遍历函数
void inorder(struct TreeNode* root) {
if (root != NULL) {
inorder(root->left);
printf("%d\n", root->val);
inorder(root->right);
}
}
// 主函数
int main() {
int N;
scanf("%d", &N);
struct TreeNode* root = NULL;
for (int i = 0; i < N; i++) {
int num;
scanf("%d", &num);
if (num >= 1 && num <= 500) {
root = insert(root, num);
}
}
inorder(root);
return 0;
}
#我的实习求职记录#
查看2道真题和解析

