剑指offer ——重建二叉树

Posted oscar67

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指offer ——重建二叉树相关的知识,希望对你有一定的参考价值。

p62 输入前序和中序遍历的结果(不包含重复的数字),重建二叉树。

主要是分析两个序列的规律,然后用递归的方式找到每一个根节点,从而完成构建。

#include<iostream>
#include <vector>
#include <set>
#include <functional>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include <list>
#include <map>
#include <stack>
#include <algorithm>
#include<iomanip>
using namespace std;

class Node{
public:
	Node(int a = 0, Node* b = nullptr, Node* c = nullptr) :value(a), left(b),right(c){}
	int value;
	Node* left,*right;
};

Node* createTree(vector<int>& Pre, vector<int>& Mid, int pStart, int pEnd, int mStart, int mEnd)
{
	if (pStart < 0 || pEnd >= Pre.size() || mStart < 0 || mEnd >= Mid.size() || pStart > pEnd || mStart > mEnd)
		return nullptr;
	if (pEnd - pStart != mEnd - mStart)
	{
		cout << "Error : nums can‘t match " << endl;
		return nullptr;
	}
	int value = Pre[pStart];
	Node* root = new Node(value);
	int pos = mStart;
	for (; pos <= mEnd; pos++)
		if (Mid[pos] == value)
			break;

	//判断是否存在错误
	if (pos > mEnd)
	{
		cout << "Error : Cann‘t find the root " << endl;
		delete root;
		root = nullptr;
		return nullptr;
	}

	root->left = createTree(Pre, Mid, pStart + 1, pStart + pos - mStart, mStart, pos - 1);
	root->right = createTree(Pre, Mid, pStart + pos - mStart+1, pEnd, pos+1, mEnd);

	return root;
}
Node* solution(vector<int>& a, vector<int>& b)
{
	return createTree(a, b, 0, a.size() - 1, 0, b.size() - 1);
}

void printTree(Node* root,int length=0)
{
	if (root == nullptr)
		return;

	if (root->left != nullptr)
		printTree(root->left, length + 1);

	for (int i = 0; i < length; i++)
		cout << " ";
	cout << root->value << endl;


	if (root->right != nullptr)
		printTree(root->right, length + 1);

}
int main(int argc, char** args)
{
	vector<int> a = { 1, 2, 4, 7, 3, 5, 6 ,8};
	vector<int> b = { 4, 7, 2, 1, 5, 3, 8, 6 };
	Node* root = solution(a, b);

	printTree(root);
	system("pause");
	return 0;
}

  

以上是关于剑指offer ——重建二叉树的主要内容,如果未能解决你的问题,请参考以下文章

剑指offer重建二叉树python

剑指offer重建二叉树

《剑指offer》— JavaScript重建二叉树

剑指 Offer 07. 重建二叉树(java解题)

剑指Offer07 重建二叉树

重建二叉树-剑指Offer