summaryrefslogtreecommitdiff
path: root/tree
diff options
context:
space:
mode:
authorMichael Hunteman <michael@huntm.net>2023-09-23 12:53:46 -0500
committerMichael Hunteman <michael@huntm.net>2023-10-21 21:48:03 -0500
commit9891f38ddcca971fa21ab61e7a70832c8c877b0a (patch)
tree1e820435b42c5c8187bb6d17b3ff1c204c933c1a /tree
Initial commitHEADmaster
Diffstat (limited to 'tree')
-rw-r--r--tree/data_structures.h14
-rw-r--r--tree/node.c29
-rw-r--r--tree/tree.c54
3 files changed, 97 insertions, 0 deletions
diff --git a/tree/data_structures.h b/tree/data_structures.h
new file mode 100644
index 0000000..dbc7bdc
--- /dev/null
+++ b/tree/data_structures.h
@@ -0,0 +1,14 @@
+#ifndef DATA_STRUCTURES_H
+#define DATA_STRUCTURES_H
+
+struct node {
+ int val;
+ struct node *left;
+ struct node *right;
+};
+
+extern struct node *root;
+
+struct node *insert(struct node* cur, int val);
+
+#endif
diff --git a/tree/node.c b/tree/node.c
new file mode 100644
index 0000000..c0d7738
--- /dev/null
+++ b/tree/node.c
@@ -0,0 +1,29 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include "data_structures.h"
+
+struct node *root = NULL;
+
+struct node
+*create(int val)
+{
+ struct node *tmp = malloc(sizeof(struct node));
+ tmp->val = val;
+ tmp->left = NULL;
+ tmp->right = NULL;
+ return tmp;
+}
+
+struct node
+*insert(struct node *cur, int val)
+{
+ if (cur == NULL) {
+ return create(val);
+ }
+ if (val < cur->val) {
+ cur->left = insert(cur->left, val);
+ } else if (val > cur->val) {
+ cur->right = insert(cur->right, val);
+ }
+ return cur;
+}
diff --git a/tree/tree.c b/tree/tree.c
new file mode 100644
index 0000000..82b4544
--- /dev/null
+++ b/tree/tree.c
@@ -0,0 +1,54 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include "data_structures.h"
+
+void
+pre_order(struct node *cur)
+{
+ if (cur == NULL) {
+ return;
+ }
+ printf("%d ", cur->val);
+ pre_order(cur->left);
+ pre_order(cur->right);
+}
+
+void
+in_order(struct node *cur)
+{
+ if (cur == NULL) {
+ return;
+ }
+ in_order(cur->left);
+ printf("%d ", cur->val);
+ in_order(cur->right);
+}
+
+void
+post_order(struct node *cur)
+{
+ if (cur == NULL) {
+ return;
+ }
+ post_order(cur->left);
+ post_order(cur->right);
+ printf("%d ", cur->val);
+}
+
+int
+main()
+{
+ struct node *root = NULL;
+ root = insert(root, 10);
+ int val, n = 0;
+ printf("How many integers do you want to add to root with val 10?\n");
+ scanf("%d", &n);
+ for (int i = 0; i < n; ++i) {
+ printf("Enter a number \n");
+ scanf("%d", &val);
+ insert(root, val);
+ in_order(root);
+ printf("\n");
+ }
+ return 0;
+}