利用递归遍历算法建立一颗二元树,输出先序遍历序列及该二元树中全部的叶子节点 c语言
时间: 2024-03-17 16:41:04 浏览: 132
好的,以下是利用递归遍历算法建立一棵二叉树,输出先序遍历序列及该二叉树中全部叶子节点的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
if (preorderSize == 0 || inorderSize == 0) {
return NULL;
}
int rootVal = preorder[0];
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = rootVal;
int i;
for (i = 0; i < inorderSize; i++) {
if (inorder[i] == rootVal) {
break;
}
}
root->left = buildTree(preorder + 1, i, inorder, i);
root->right = buildTree(preorder + 1 + i, preorderSize - i - 1, inorder + i + 1, inorderSize - i - 1);
return root;
}
void preorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void getLeafNodes(struct TreeNode* root, int* result, int* returnSize) {
if (root == NULL) {
return;
}
if (root->left == NULL && root->right == NULL) {
result[(*returnSize)++] = root->val;
return;
}
getLeafNodes(root->left, result, returnSize);
getLeafNodes(root->right, result, returnSize);
}
int main() {
int preorder[] = {1, 2, 4, 5, 3, 6, 7};
int inorder[] = {4, 2, 5, 1, 6, 3, 7};
int preorderSize = sizeof(preorder) / sizeof(int);
int inorderSize = sizeof(inorder) / sizeof(int);
struct TreeNode *root = buildTree(preorder, preorderSize, inorder, inorderSize);
preorderTraversal(root);
printf("\n");
int leafNodes[preorderSize];
int returnSize = 0;
getLeafNodes(root, leafNodes, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", leafNodes[i]);
}
printf("\n");
return 0;
}
```
以上代码中,`buildTree` 函数用于建立二叉树,`preorderTraversal` 函数用于输出二叉树的先序遍历序列,`getLeafNodes` 函数用于获取二叉树中所有的叶子节点。`main` 函数中定义了二叉树的先序遍历数组 `preorder` 和中序遍历数组 `inorder`,并分别计算了它们的大小。在 `main` 函数中,首先建立二叉树,然后输出先序遍历序列和所有叶子节点。
阅读全文