树与BST:术语、遍历和高度
根、层次、遍历顺序与搜索序分别理解。
逐步查看固定输入下的数据变化。这里回放本地C程序的实际结果;下载源码后可修改输入并重新编译。
实际运行范围
当前固定输入有 53 项断言通过。本次实验创建的动态节点已全部释放。当前结果对应本章固定输入,改变输入后请重新编译核对。
编译器:Zig 0.14.1 cc;标准:C11;本轮环境:Windows。
编译:zig cc -std=c11 -Wall -Wextra -Werror -pedantic c-dsa-tree.c dsa.c -o demo.exe,再运行demo.exe。
本章完整入口
#include "test_support.h"
int main(void){
puts("MBSKY | mbsky.com | independently authored C11 case");
Tree nodes[5]={{1,NULL,NULL},{2,NULL,NULL},{3,NULL,NULL},{4,NULL,NULL},{5,NULL,NULL}};nodes[0].left=&nodes[1];nodes[0].right=&nodes[2];nodes[1].left=&nodes[3];nodes[1].right=&nodes[4];int expected[4][5]={{1,2,4,5,3},{4,2,5,1,3},{4,5,2,3,1},{1,2,3,4,5}};int out[CAP];for(int mode=0;mode<4;++mode){CHECK(tree_walk(nodes,mode,out,CAP)==5);equal_values(out,expected[mode],5);state((const char*[]) {"preorder","inorder","postorder","levelorder"}[mode],out,5);}CHECK(tree_height(nodes)==2&&tree_height(NULL)==-1);CHECK(tree_walk(NULL,0,out,CAP)==0);Tree *root=NULL;int values[]={50,30,70,20,40,60,80};for(size_t i=0;i<7;++i)CHECK(bst_insert(&root,values[i]));CHECK(bst_insert(&root,40));CHECK(tree_walk(root,1,out,CAP)==7);equal_values(out,(int[]){20,30,40,50,60,70,80},7);state("BST-sorted",out,7);CHECK(bst_find(root,40)&&!bst_find(root,99));allocation_fail_after(0);CHECK(!bst_insert(&root,99));allocation_fail_after(-1);CHECK(!bst_find(root,99));tree_clear(&root);for(int i=0;i<6;++i)CHECK(bst_insert(&root,i));CHECK(tree_height(root)==5);state("ordered-insertion-height",(int[]){tree_height(root)},1);tree_clear(&root);
return finish();
}