Insert
الدرس 10 من 13 في دورة Binary Tree - سلسلة هياكل البيانات #3 على Coddy.
التحدي
سهلأضف إلى BinaryTree طريقة insert تأخذ عدداً صحيحاً وتدرجه في شجرة بحث ثنائية. (القيم الأصغر من أو المساوية للعقدة الحالية تذهب إلى الشجرة الفرعية اليسرى؛ والقيم الأكبر تذهب إلى الشجرة الفرعية اليمنى.)
جرّب بنفسك
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "binarytree.h"
int main() {
BinaryTree bt;
BinaryTree_init(&bt);
char line[256];
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\r\n")] = '\0';
char* cmd = strtok(line, " \t");
if (!cmd) continue;
if (strcmp(cmd, "insert") == 0) {
char* arg = strtok(NULL, " \t");
if (arg) BinaryTree_insert(&bt, atoi(arg));
}
if (strcmp(cmd, "inOrderPrint") == 0) {
BinaryTree_inOrderPrint(&bt);
}
}
return 0;
}