根据二叉树的先序和中序来构建二叉树

来源:互联网 发布:linux编译php扩展 编辑:程序博客网 时间:2024/06/06 17:51

根据二叉树的先序和中序 来构建二叉树然后再输出二叉树的后序这是笔试题中常见的题目。
其实思想很简单 string pre 为先序的字符串 string in为中序的字符串
pre[0]为树根 找到pre[0]在in中的位置(下标从0开始)为index,则 index为左子树的长度 pre中下标1~index为左子树的先序 下标从index+1~最后为右字数的先序。in中下标0~index-1为左子树的 中序 in中下标index+1~最后为右子树的中序 这样每次都可以由一颗树的先序序列和中序序列确定其左子树和右子树的先序和中序序列 而先序序列中的一个元素为根元素 每次都确定一个根元素,直到整个序列为空

// pre-in-construct-tree.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <string>using namespace std;struct TreeNode{    char val;    TreeNode *left;    TreeNode *right;};/*create tree by preorder and inorder string */TreeNode *createTree(string pre, string in){    TreeNode *t = NULL;    if (pre.length() > 0)    {        t = new TreeNode();        t->val = pre[0];        int index = in.find(pre[0]);//find the root node in the inorder string        t->left = createTree(pre.substr(1, index), in.substr(0, index));        t->right = createTree(pre.substr(index + 1), in.substr(index + 1));    }    return t;}void postOrder(TreeNode *root){    if (root)    {        postOrder(root->left);        postOrder(root->right);        cout << root->val << " ";    }    else return;}void destroyTree(TreeNode*root){    if (root)    {        destroyTree(root->left);        destroyTree(root->right);        delete root;    }    else return;}int main(){    string pre = {'1','2','3','4','5','6','7'};    string in = { '3','2','4','1','6','5','7' };    TreeNode *root = createTree(pre, in);    postOrder(root);    destroyTree(root);    system("pause");    return 0;}
0 0