根据先序遍历和中序遍历重建二叉树

题目

思路

  • 用先序遍历的方法找到当前根节点,然后再将问题划分为左子数和右子树的问题。递归的思想。

代码

#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>
#include <stdio.h>
#include <numeric>
#include <algorithm>
#include <functional>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <memory>
#include <memory.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
typedef unsigned char uchar;

// #define G_DEBUG
// 定义unordered_set<pair<int,int>, pairhash> sets时会用到
struct pairhash {
public:
	template <typename T, typename U>
	std::size_t operator()(const std::pair<T, U> &x) const
	{
		return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
	}
};

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int findIdx(vector<int>& nums, int target)
{
	for (int i = 0; i < nums.size(); i++)
		if (target == nums[i])
			return i;

	return -1;
}

TreeNode* solve(vector<int>& pre, vector<int>& vin,
								int pre_left, int pre_right,
								int vin_left, int vin_right)
{
	if (pre_left >= pre.size() || vin_left >= vin.size()
		|| pre_right < 0 || vin_right < 0)
		return NULL;
	if (pre_left > pre_right || vin_left > vin_right)
		return NULL;

	TreeNode *head = new TreeNode( pre[pre_left] );
	
	int mid_idx = findIdx(vin, pre[pre_left]);
	

	head->left = solve(pre, vin, pre_left + 1, pre_left + mid_idx - vin_left, vin_left, mid_idx - 1);
	head->right = solve(pre, vin, pre_left + mid_idx - vin_left + 1, pre_right, mid_idx + 1, vin_right);
	return head;
}

TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
	TreeNode *head = solve(pre, vin, 0, pre.size() - 1, 0, vin.size() - 1);
	return head;
}

int main()
{

#ifdef G_DEBUG
	// 调试使用
	ifstream file("data.txt");
	int N = 0, K = 0;
	file >> N >> K;
	vector<int> nums(N, 0);
	for (int i = 0; i < N; i++)
	{
		file >> nums[i];
	}
	
	file.close();
#else

#endif
	
	vector<int> pre = { 1, 2, 4, 7, 3, 5, 6, 8 };
	vector<int> vin = { 4, 7, 2, 1, 5, 3, 8, 6 };

	//vector<int> pre = { 1 };
	//vector<int> vin = { 1 };
	TreeNode *root = reConstructBinaryTree( pre, vin );

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u012526003/article/details/82855801