又中序遍历和后序遍历还原二叉树

又中序遍历和后序遍历还原二叉树

根据一棵树的中序和先序遍历的结果可以还原一棵唯一的二叉树。
题目要求:
设计一个程序,根据二叉树的先根序列和中根序列创建一棵用左右指针表示的二叉树
例如:先根序列为 ABDGCEF#, 中根序列为 DGBAECF# (#表示结束)。然后用程序构造一棵二叉树。
思路:

流程图
MY CODE


#include<iostream>
#include<stdio.h>
#include<string>
#include<algorithm>
using namespace std;
string preorder = "";
string inorder = "";
//node of binary tree
struct Node{
	char val;
	Node *left, *right;
};

//display an binary tree by postorder
void display(Node *n){
	if (n == NULL) return;
	if (n->left != NULL) display(n->left);
	if (n->right != NULL) display(n->right);
	cout << n->val << " ";
}

//check the input return false mean can't not build an tree by those input
bool cheackinput1(string str1, string str2){
	string t1 = str1;
	string t2 = str2;
	int li = t1.length() - 1;	//last index
	if (t1[li] != '#' || t2[li] != '#') return false;
	sort(t1.begin(), t1.end());
	sort(t2.begin(), t2.end());
	if (t1 == t2) return true;
	return false;
}

//caculate the length of begin to precifed node in inorder list
//return -1 if can't not find target in the range, that mean the input is worng!
int callength(char targer, int l, int r){
	for (int i = l; i <= r; i++){
		if (inorder[i] == targer) return i - l;
	}
	return -1;
}

//rebuild an binary tree by preorder and inorder 
//left and right edge of preorder input and inorder input
//the edge number shold point to the begin or last element of an array
void rebuildtree(Node *&h,int pl,int pr, int il, int ir){
	if (pl > pr){
		return;
	}
	h = new Node();	//init the node
	h->left = h->right = NULL;	
	char newval = preorder[pl];
	h->val = newval;
	if (pl == pr) { //it is the leaf node
		return;
	}	
	int leftlen = callength(preorder[pl], il, ir);
	if (leftlen == -1) {	//caculate the size of left tree
		cout << "the input may worng !" << endl;
		return;
	}
	if (leftlen != 0){	//have left child tree
		rebuildtree(h->left, pl + 1, pl + leftlen, il, il + leftlen - 1);
	}
	rebuildtree(h->right,pl+leftlen+1, pr, il+leftlen+1, ir );	//rebuild right child tree
	return;
}



//test of rebuild tree
void test1(){
	cout << "Please input the preorder of the tree > ";
	cin >> preorder;
	cout << "Please input the inorder of the tree > ";
	cin >> inorder;
	if (!cheackinput1(preorder, inorder)){
		cout << "the input may worng !";
		return;
	}
	Node* head = NULL;
	int len = inorder.length()-2; //ignore last char '#'
	rebuildtree(head, 0, len, 0, len);
	display(head);
	cout << endl;
	return;
}

int main(){
	test1();
	return 0;
}

/* test1 mock_data1
ABDEFCGHI# 
DBFEACHGI#
*/
发布了90 篇原创文章 · 获赞 31 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/BlackCarDriver/article/details/90019854
今日推荐