[数据结构]树与二叉树_2

📅 2026/7/4 4:22:49
[数据结构]树与二叉树_2
01查找值为x的结点代码思想采用深度优先策略先判断当前结点是否为目标结点若不是则递归遍历其孩子子树孩子子树遍历完毕后递归遍历兄弟结点。代码实现CSTree Search(CSTree T, int x) {if (!T) return NULL;if (T-data x) return T;CSTree p Search(T-firstchild, x);return p ? p : Search(T-nextsibling, x);}02插入孩子最右位置代码思想若目标结点无孩子新结点直接作为其第一个孩子若已有孩子遍历兄弟链至末尾将新结点挂载为最后一个兄弟。代码实现void InsertChild(CSTree p, int x) {if (!p) return;CSTree newNode CreateNode(x);if (!p-firstchild)p-firstchild newNode;else {CSTree q p-firstchild;while (q-nextsibling) q q-nextsibling;q-nextsibling newNode;}}03删除以x为根的子树代码思想递归查找目标结点找到后先递归删除其所有孩子与兄弟结点再释放目标结点内存并置空指针避免野指针。代码实现void DeleteSubTree(CSTree *T, int x) {if (!*T) return;if ((*T)-data x) {DeleteSubTree((*T)-firstchild, x);DeleteSubTree((*T)-nextsibling, x);free(*T);*T NULL;return;}DeleteSubTree((*T)-firstchild, x);DeleteSubTree((*T)-nextsibling, x);}