From 7211fa15f26f5b91bda3c2f1e3e0588e97e9efcc Mon Sep 17 00:00:00 2001 From: ivy-Lee-2333 Date: Mon, 19 Feb 2024 11:04:25 +0000 Subject: [PATCH] add assignment/C/lixinyi/work2. Signed-off-by: ivy-Lee-2333 --- assignment/C/lixinyi/work2 | 111 +++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 assignment/C/lixinyi/work2 diff --git a/assignment/C/lixinyi/work2 b/assignment/C/lixinyi/work2 new file mode 100644 index 0000000..daff2d2 --- /dev/null +++ b/assignment/C/lixinyi/work2 @@ -0,0 +1,111 @@ +#include +#include +#include +#include + +typedef double (*func_t)(double); + +// 返回funcs中所有函数的复合函数,即f(x) = fn(...f2(f1(x))) +double composite(func_t funcs[],int n,double input) +{ + double result = input; + for(int i=0;ival=val; + node->left=NULL; + node->right=NULL; + return node; +} + +// 插入一个节点,如果val比当前节点值小,插入左子树,否则插入右子树 +void insert(struct Node *root, int val) +{ + if(valval){ + if(root->left==NULL){ + root->left=newNode(val); + } + else{ + insert(root->left,val); + } + } + else{ + if(root->right==NULL){ + root->right=newNode(val); + } + else{ + insert(root->right,val); + } + } +} + +// 遍历二叉树,先遍历左儿子,然后遍历自己,最后遍历右儿子,将遍历结果存入数组中,返回数组长度 +int traverse(struct Node *root, int *arr) +{ + if(root==NULL){ + return 0; + } + int left_len=traverse(root->left,arr); + arr[left_len]=root->val; + int right_len=traverse(root->right,arr+left_len+1); + return left_len+right_len+1; +} + +// 释放二叉树的内存 +void freeTree(struct Node *root) +{ + if(root==NULL){ + return; + } + freeTree(root->left); + freeTree(root->right); + free(root); +} + +void check2() +{ + struct Node *root = newNode(5); + insert(root, 3); + insert(root, 7); + insert(root, 2); + insert(root, 4); + insert(root, 6); + insert(root, 8); + int arr[7]; + int len = traverse(root, arr); + assert(len == 7); + for (int i = 0; i < len; i++) + assert(arr[i] == i + 2); + freeTree(root); +} + +int main() +{ + check1(); + check2(); + puts("Tests passed!"); + return 0; +} \ No newline at end of file -- Gitee