c++代码实现:通过先序和中序遍历建立二叉树
时间: 2023-05-28 07:04:48 浏览: 70
#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode{
char val;
struct TreeNode *left;
struct TreeNode *right;
}TreeNode;
TreeNode* buildTree(char* preorder, int prestart, int preend, char* inorder, int instart, int inend){
if(prestart > preend || instart > inend) return NULL;
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = preorder[prestart];
int index = instart;
while(index <= inend && inorder[index] != preorder[prestart]){
index++;
}
root->left = buildTree(preorder, prestart+1, prestart+index-instart, inorder, instart, index-1);
root->right = buildTree(preorder, prestart+index-instart+1, preend, inorder, index+1, inend);
return root;
}
void inorderTraversal(TreeNode* root){
if(root == NULL) return;
inorderTraversal(root->left);
printf("%c ", root->val);
inorderTraversal(root->right);
}
int main(){
char preorder[] = {'A', 'B', 'D', 'E', 'C', 'F', 'G'};
char inorder[] = {'D', 'B', 'E', 'A', 'F', 'C', 'G'};
TreeNode* root = buildTree(preorder, 0, 6, inorder, 0, 6);
inorderTraversal(root);
return 0;
}
阅读全文