您的位置:首页 > 其它

根据二叉树的前序和中序序列来重建二叉树

2012-08-24 12:24 375 查看
根据二叉树的前序和中序序列来重建二叉树,输出其后序序列

这是面试笔试中经常遇到的问题

关键要理解在前序和中序序列中找左右子树的前序和中序序列的方法,利用递归实现

另外字符串的标准库函数要活用

[cpp] view
plaincopy

#include <iostream>

#include <string>

using namespace std;

struct TreeNode{

char val;

TreeNode *left,*right;

};

TreeNode * bulidTree(string pre,string in){

TreeNode * root =NULL;

if (pre.length() > 0)

{

root = new TreeNode;

root->val = pre[0];

int index = in.find(pre[0]);

//关键要理解再先序和后序序列中找左右子树的先序和后序序列的方法,利用递归实现

root->left = bulidTree(pre.substr(1,index),in.substr(0,index));

root->right = bulidTree(pre.substr(index+1),in.substr(index+1));

}

return root;

}

void PostTraverse(TreeNode * root){

if (root != NULL)

{

PostTraverse(root->left);

PostTraverse(root->right);

cout<<root->val;

}

}

int main(){

string prestr,instr;

while(cin>>prestr>>instr){

TreeNode * root =bulidTree(prestr,instr);

PostTraverse(root);

cout<<endl;

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: