用c语言表示1.设二叉树采用二叉链表存储,编写函数,对二叉树中每个元素值为X的结点,删除以它为根的子树,并释放相应空间。 2.假设二叉树采用二叉链表存储结构,求二叉树b中结点值为x的结点的层次(或深度)
时间: 2024-12-14 20:22:50 浏览: 42
1. 在 C 语言中,删除二叉树中所有值为 X 的节点通常涉及遍历整个二叉链表。这里是一个简单的示例,我们将展示如何递归地删除满足条件的节点并释放其内存:
```c
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 删除值为 X 的节点(仅删除根节点)
void delete_subtree(TreeNode** root, int x) {
if (*root == NULL) return; // 如果当前节点为空,直接返回
// 递归处理左右子树
delete_subtree(&(*root)->left, x);
delete_subtree(&(*root)->right, x);
// 当前节点值等于 x,删除节点
if ((*root)->val == x) {
free(*root); // 释放节点内存
*root = NULL; // 更新根指针
}
}
// 使用时,传入根节点指针即可
TreeNode* root = ...; // 初始化的二叉链表
int x = ...;
delete_subtree(&root, x);
```
2. 求二叉树中结点值为 x 的节点的层次(或深度),可以使用广度优先搜索 (BFS)。以下是相应的算法:
```c
#include <stdio.h>
#include <queue>
int maxDepth(TreeNode* node, int depth = 0) {
if (node == NULL) return depth; // 如果节点为空,返回当前层数
int left_depth = maxDepth(node->left, depth + 1);
int right_depth = maxDepth(node->right, depth + 1);
return left_depth > right_depth ? left_depth : right_depth; // 返回较大深度
}
// 同样需要已初始化的二叉链表根节点
TreeNode* root = ...;
int x = ...;
int result = maxDepth(root, 0);
printf("节点值为 %d 的节点的层次是 %d\n", x, result);
```
阅读全文
相关推荐
















