通过二叉树的前序遍历和中序遍历创建树
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct NODE { int nValue; struct NODE* pLeft; struct NODE* pRight; }BinaryTree; int Getxb(char* inorder,int num) { //得到根在中序遍历中的下标 for(int i=0;i<strlen(inorder);i++) { if(inorder[i] == num) return i; } return -1; } BinaryTree* CreateNode(char c) { BinaryTree* ptemp = (BinaryTree*)malloc(sizeof(BinaryTree)); ptemp->nValue = c; ptemp->pLeft = NULL; ptemp->pRight = NULL; return ptemp; } BinaryTree* CreateTree(char* pre,char* in) { if(pre == NULL || in == NULL) return NULL; if(*pre == NULL) return NULL; char szPreorder[100]; char szInorder[100]; memset(szPreorder,0,100); memset(szInorder,0,100); BinaryTree* pNode = CreateNode(pre[0]); int index = Getxb(in,pre[0]); //index等于几代表根有几个左 strncpy(szPreorder,pre+1,index); strncpy(szInorder,in,index); pNode->pLeft = CreateTree(szPreorder,szInorder); memset(szPreorder,0,100); memset(szInorder,0,100); //右的数量等于strlen-左-根(1) strncpy(szPreorder,pre+1+index,strlen(pre)-index-1); strncpy(szInorder,in+1+index,strlen(pre)-index-1); pNode->pRight = CreateTree(szPreorder,szInorder); return pNode; } void Preorder(BinaryTree* pNode) { if(pNode == NULL) return; Preorder(pNode->pLeft); Preorder(pNode->pRight); printf("%d ",pNode->nValue-48); } int main() { char szbuf1[10]; char szbuf2[10]; BinaryTree* p = CreateTree("124536","425163"); Preorder(p); return 0; }
通过二叉树的后序遍历和中序遍历创建树
只有创建树的代码换了
BinaryTree* CreateTree(char* post,char* in) { if(post == NULL || in == NULL) return NULL; if(*post == NULL) return NULL; //根节点在后序遍历的最后 int num = strlen(post)-1; char szInorder[100]; char szPostorder[100]; memset(szInorder,0,100); memset(szPostorder,0,100); BinaryTree* pTree = CreateNode(post[num]); //得到中序遍历中根的下标,index代表根有几个左 int index = Getxb(in,post[num]); strncpy(szInorder,in,index); strncpy(szPostorder,post,index); pTree->pLeft = CreateTree(szPostorder,szInorder); memset(szInorder,0,100); memset(szPostorder,0,100); //右的数量等于strlen-左-根(1) strncpy(szInorder,in+1+index,strlen(in)-1-index); strncpy(szPostorder,post+index,strlen(in)-1-index); pTree->pRight = CreateTree(szPostorder,szInorder); return pTree; }
原文地址:https://www.cnblogs.com/TheQi/p/9127478.html
时间: 2024-10-10 14:32:58