Sicily 1935 二叉樹重建

數據結構的簡單題,對幫助理解二叉樹的遍歷蠻有幫助的。


#include <iostream>
#include <cstring>

using namespace std;

struct node
{
	char val;
	node * left;
	node * right;
};

node * build(int n, char * pre, char * in)
{
    //注意strchr返回的是指向那個字符的指針,要減去頭指針 
	if (n <= 0) return NULL;
	
	node * ans = new node;
	ans->val = pre[0];
	int order = strchr(in, pre[0]) - in;
	ans->left = build(order, pre+1, in);
	ans->right = build(n-order-1, pre+order+1, in+order+1);//這裏不能用[],要用指針的加減法 
	
	
	return ans;
}

void BFS(node * root)
{
	if (root == NULL) return;
	
	node* q[30];//q是輸出序列 
	q[0] = root;
	
	int n = 0, o = 1;//n代表輸出節點數,o代表總結點數 
	
	while (n < o)
	{
		node * temp = q[n];
		n++;
		
		cout << temp->val;
		if (temp->left != NULL) q[o++] = temp->left;
		if (temp->right != NULL) q[o++] = temp->right;
	}
}

void deleteTree(node * root)
{
	if (root == NULL) return;
	if (root->left != NULL) deleteTree(root->left);
	if (root->right != NULL) deleteTree(root->right);
	delete root;
}

char preorder[30], inorder[30];
 
int main()
{
	int t;
	
	cin >> t;
	while (t --)
	{
		cin >> preorder >> inorder;
		int len = strlen(preorder);
		node * root = build(len, preorder, inorder);
		BFS(root);
		cout << endl; 
		deleteTree(root);
	}
	
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章