// test20.cpp : 定義控制台應用程序的入口點。
//
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
struct TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> in) {
//先通過前序遍歷找到跟節點
//再通過跟節點把中序遍歷的結果分為左子樹tree_left和右子樹tree_right
//tree_left在前序遍歷中的第一個節點就是跟節點的左孩子
//tree_right在前序遍歷中的第一個節點就是跟節點的右孩子
if (pre.size() == 0) return NULL;
/*if (pre.empty() || in.empty() || pre.size() != in.size())
return NULL;*/
TreeNode* root = new TreeNode(pre[0]); //前序遍歷的第一個節點就是跟節點
if (pre.size() == 1) return root;
vector<int> in_left, in_right;//中序遍歷中的左子樹和右子樹
vector<int> pre_left, pre_right;//前序遍歷中的左子樹和右子樹
int num_left=0, num_right=0; //分別存儲左子樹和右子樹的個數
int cur = pre[0]; //存儲謙虛遍歷中的第一個值,根據這個值在將中序遍歷分為左子樹和右子樹
int pos = 0;//中序遍歷中cur中的位置
for (int i = 0;i < in.size();i++) //計算中序遍歷的左子樹和右子樹
{
if (in[i] == cur)
pos = i;
}
for (int i = 0;i < in.size();i++)
{
if (i < pos)
{
in_left.push_back(in[i]);
num_left++;
}
if (i > pos)
{
in_right.push_back(in[i]);
num_right++;
}
}
for (int i = 1;i < pre.size();i++) //計算先序遍歷的左子樹和右子樹
{
if (num_left)
{
pre_left.push_back(pre[i]);
--num_left;
}
else if (num_right)
{
pre_right.push_back(pre[i]);
--num_right;
}
else
{
}
}
//if(!pre_left.empty()&&root!=NULL)
root->left=reConstructBinaryTree(pre_left,in_left);
//if(!pre_right.empty() && root != NULL)
root->right = reConstructBinaryTree(pre_right,in_right);
return root;//最后返回根節點,這點很重要,之前都是因為這個一直調試不通過
}
void preOrder(TreeNode* &T)
{
if (T == NULL) return;
else
{
cout << T->val << " ";
preOrder(T->left);
preOrder(T->right);
}
}
void preCreate(TreeNode * &T)
{
int num;
cin >> num;
if (num == 0) return;
else
{
T = new TreeNode(num);
preCreate(T->left);
preCreate(T->right);
}
}
};
int main()
{
Solution so;
TreeNode *T;
vector<int> pre = { 1,2,4,7,3,5,6,8 };
vector<int> in = { 4,7,2,1,5,3,8,6 };
//vector<int> pre = {1,2};
//vector<int> in = {2,1};
//so.preCreate(T);
// cout << "創建成功!" << endl;
T = so.reConstructBinaryTree(pre,in);
cout << "構建成功" << endl;
cout << "前序遍歷二叉樹:" << endl;
so.preOrder(T);
cout << endl;
return 0;
}
