用c++写一个基于先序遍历的二叉树构造算法
时间: 2024-04-30 17:17:27 浏览: 111
好的,根据您的问题,我可以为您提供如下的基于先序遍历的二叉树构造算法的C语言代码案例供您参考:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node Node;
struct Node {
int data;
Node *left;
Node *right;
};
int i = 0;
Node* createNode(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
Node* buildTree(int *preorder, int size) {
if (i >= size) {
return NULL;
}
Node *root = createNode(preorder[i++]);
if (preorder[i] < root->data) {
root->left = buildTree(preorder, size);
}
if (preorder[i] > root->data) {
root->right = buildTree(preorder, size);
}
return root;
}
void printInorder(Node *node) {
if (node == NULL) {
return;
}
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
int main() {
int preorder[] = {10, 5, 1, 7, 40, 50};
int size = sizeof(preorder) / sizeof(preorder[0]);
Node *root = buildTree(preorder, size);
printf("Inorder traversal of the constructed tree is: ");
printInorder(root);
return 0;
}
```
该算法基于先序遍历的二叉树构造方法,可以将一颗二叉树的先序遍历结果转化为该二叉树,具体的实现细节可以查看上述的C语言代码案例。
阅读全文