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

根据二叉树的先序和中序 来构建二叉树然后再输出二叉树的后序这是笔试题中常见的题目。
其实思想很简单 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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hebastast

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值