二叉树遍历

来源:互联网 发布:网络安全法全文 编辑:程序博客网 时间:2024/05/17 03:14

输入前序遍历序列和中序遍历序列,输出后序遍历序列

#include <iostream>#include <cstring>using namespace std;struct TreeNode {char ch;TreeNode *lchild;TreeNode *rchild;};void PostTree(char *preStr,char *inStr,int length){int rootidx = 0;TreeNode *root = new TreeNode;if(length == 0){return;}root->ch = *preStr;for(rootidx = 0; rootidx <length;rootidx++){if(*preStr == inStr[rootidx])  //寻找中序遍历序列中根节点的索引{break;}}PostTree(preStr + 1,inStr,rootidx);  //左子树递归PostTree(preStr+rootidx+1,inStr+rootidx+1,length-rootidx-1);  //右子树递归cout<<root->ch;return;}int main(){char pretree[26] = {'\0'};  //存储先序遍历结果char intree[26] = {'\0'};//存储中序遍历结果char temp[26] = {0}; while(cin.getline(temp,26)){strncpy(pretree,temp,26);   cin.getline(temp,26);strncpy(intree,temp,26);PostTree(pretree,intree,strlen(pretree));cout<<endl;}return 0;}


0 0
原创粉丝点击