1、按先序序列构造一棵二叉链表表示的二叉树T。 2、对这棵二叉树进行中序遍历。(递归算法) 3、求二叉树的高度。 4、求二叉树叶结点数目。 5、将二叉树每个结点的左右子树交换位置。根据以上条件给出C语言代码,从键盘输入
时间: 2024-12-17 13:25:12 浏览: 40
首先,以下是使用C语言实现上述功能的部分代码:
1. **按先序序列构造二叉链表**(假设先序遍历数组pre[]存储了节点值,数组长度为n,pre[0]为根节点,前缀sum[]存储了前i个元素的累加和用于查找子节点索引):
```c
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
TreeNode* buildTree(int pre[], int n) {
if (n == 0) return NULL;
TreeNode* root = new TreeNode(pre[0]);
int i = 1, sum = 0;
for (; i < n && pre[i]; ++i) {
while (sum <= pre[i]) {
sum += pre[++root->left->val];
}
root->right = new TreeNode(pre[i]);
++sum;
}
return root;
}
```
2. **中序遍历(递归)**:
```c
void inorderTraversal(TreeNode* node) {
if (node != NULL) {
inorderTraversal(node->left);
printf("%d ", node->val); // 输出节点值
inorderTraversal(node->right);
}
}
```
3. **求二叉树高度**:
```c
int height(TreeNode* root) {
if (root == NULL) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return MAX(leftHeight, rightHeight) + 1;
}
int main() {
// 先构建树...
int heightResult = height(root);
printf("树的高度: %d\n", heightResult);
return 0;
}
```
4. **求二叉树的叶节点数**:
```c
int countLeaves(TreeNode* node, int count) {
if (node == NULL) return count;
if (node->left == NULL && node->right == NULL) count++;
return countLeaves(node->left, count) + countLeaves(node->right, count);
}
int main() {
int leafCount = countLeaves(root, 0);
printf("叶节点数: %d\n", leafCount);
return 0;
}
```
5. **交换每个节点的左右子树**:
```c
void swapChildren(TreeNode* node) {
if (node != NULL) {
TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
swapChildren(node->left);
swapChildren(node->right);
}
}
int main() {
// 在这里调用swapChildren(root)函数
printf("交换后的树结构...\n");
return 0;
}
```
请注意,为了完整实现所有功能,上述代码需要在main函数中整合并处理用户输入。此外,`MAX()`和`new`在C语言中可能需要自定义,因为标准库中一般没有提供。你可以选择使用宏或者头文件如`stdlib.h`或`malloc.h`。
阅读全文
相关推荐


















