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;
}
测试结果: