diff --git a/assignment/C/lixinyi/work2 b/assignment/C/lixinyi/work2 new file mode 100644 index 0000000000000000000000000000000000000000..daff2d29209f3419b71bb90b4c57cebc8f18d2ad --- /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