Construct Binary Tree from Preorder and Inorder Traversal

Description:

Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.

分析:
先序遍历和中序遍历可以确定一颗二叉树。思想方法来自于网上

#include <iostream>
#include <vector>
#include <stack>

#define Elementype int

using namespace std;

using iter_int = vector<int>::iterator;


typedef struct TreeNode //树结点
{
    Elementype  val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(Elementype x) : val(x), left(nullptr), right(nullptr) {}
} *Tree;

Tree BuildTree(iter_int pre_b,iter_int pre_e,iter_int in_b, iter_int in_e)
{
    //终止条件
    if (pre_b == pre_e)
        return nullptr;
    if (in_b == in_e)
        return nullptr;

    auto root = new TreeNode(*pre_b);
    auto location = find(in_b, in_e, *pre_b);
    auto leftsize = distance(in_b, location);
    root->left = BuildTree(pre_b + 1, pre_b + leftsize + 1, in_b, in_b + leftsize);
    root->right = BuildTree(pre_b + leftsize + 1, pre_e, location + 1, in_e);

    return root;
}

Tree ConstructBinaryTree(vector<int>& pre, vector<int>&in)
{
    return BuildTree(pre.begin(), pre.end() , in.begin(), in.end() );
}

void PreorderTraversal(Tree root)   //前序遍历
{
    stack<Tree> sk;
    sk.push(root);


    while (!sk.empty())
    {
        auto p = sk.top();
        cout << p->val << " ";
        sk.pop();

        if (p->right)
            sk.push(p->right);
        if (p->left)
            sk.push(p->left);
    }
    cout << endl;
}

void InorderTraversal(Tree root)    //中序遍历
{
    stack<Tree> sk;
    Tree p = root;
    while (p)
    {
        sk.push(p);
        p = p->left;
    }
    while (!sk.empty())
    {
        p = sk.top();
        cout << p->val << " ";
        sk.pop();
        if (p->right)
            InorderTraversal(p->right); 
    }
}

int main()
{   
    vector<int> preorder = { 7, 10, 4, 3, 1, 2, 8, 11 };
    vector<int> inorder = { 4, 10, 3, 1, 7, 11, 8, 2 };

    Tree root = ConstructBinaryTree(preorder, inorder);

    cout << "前序遍历结果: ";
    PreorderTraversal(root);
    cout << "中序遍历结果: ";
    InorderTraversal(root);
    cout << endl;

    system("pause");
    return 0;
}

测试结果:

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值