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

题目

思路

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

代码

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

littletomatodonkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值