剑指offer题目:重建二叉树
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
程序注释:根据题目要求重建二叉树,并加入三种遍历方式输出查看结果。
已在vs2013运行通过,函数reConstructBinaryTree在剑指offer牛客网也通过了。
// reconstructionbinarytree.cpp : 定义控制台应用程序的入口点。
//created by:bdf
//data:2019.4.26
#include "stdafx.h"
#include "iostream"
#include "vector"
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr){}
};
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
if (pre.empty() || vin.empty()) return nullptr;
TreeNode * root = new TreeNode(pre[0]);
int length = 0;
while (pre[0] != vin[length]) length++;
vector<int> pre_left, pre_right, vin_left, vin_right;
for (int i = 0; i<length; i++)
{
pre_left.push_back(pre[i + 1]);
vin_left.push_back(vin[i]);
}
for (int i = length + 1; i< pre.size(); i++)
{
pre_right.push_back(pre[i]);
vin_right.push_back(vin[i]);
}
root->left = reConstructBinaryTree(pre_left, vin_left);
root->right = reConstructBinaryTree(pre_right, vin_right);
return root;
}
void PreOrderTraverse(TreeNode* root)
{
if (root)
{
cout << root->val << " ";
PreOrderTraverse(root->left);
PreOrderTraverse(root->right);
}
}
void InOrderTraverse(TreeNode *root)
{
if (root)
{
InOrderTraverse(root->left);
cout << root->val << " ";
InOrderTraverse(root->right);
}
}
void PostOrderTraverse(TreeNode *root)
{
if (root)
{
PostOrderTraverse( root->left);
PostOrderTraverse( root->right);
cout << root->val << " ";
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> pre{ 1, 2, 4, 5, 3, 6, 7 };
vector<int> vin{ 4, 2, 5, 1, 6, 3, 7 };
Solution reconstruct;
TreeNode *newRoot = reconstruct.reConstructBinaryTree(pre, vin);
reconstruct.PreOrderTraverse(newRoot);
cout << endl;
reconstruct.InOrderTraverse(newRoot);
cout << endl;
reconstruct.PostOrderTraverse(newRoot);
system("pause");
return 0;
}