</pre><pre name="code" class="cpp">#include <iostream>
#include <sstream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <stack>
#include <queue>
#include <set>
#include <math.h>
#include <time.h>
/*=======================================
二叉樹重建
老掉牙的話題
========================================*/
#define flush(arr, i) memset(arr, i, sizeof(arr))
typedef long long int64;
using namespace std;
const int MAX_ITEM = 1024;
const int oo = 0x7fffffff;
//const int oo = 0x3f3f3f3f;
char preOrder[MAX_ITEM] = "abcdefghij", inOrder[MAX_ITEM] = "cbedfahgji";
struct Node
{
char data;
Node *lchild, *rchild;
Node(char key):data(key), lchild(NULL), rchild(NULL){}
};
//入口參數表示當前子樹的preOrder和inOrder
Node* reBuild(int inl, int inr, int pl, int pr)
{
if(pr < pl)
return NULL;
Node *root = new Node(preOrder[pl]);
//pos是inOrder序列中的位置,範圍注意
int pos = inl;
while(pos <= inr && inOrder[pos] != preOrder[pl])
pos++;
int len = pos - inl;
//分治法
root->lchild = reBuild(inl, pos - 1, pl + 1, pl + len);
root->rchild = reBuild(pos + 1, inr, pl + len + 1, pr);
return root;
}
//廣義表輸出
void traverse(Node *root)
{
root == NULL ? printf("*") : printf("%c", root->data);
if(!root)
return;
printf("(");
traverse(root->lchild);
printf(",");
traverse(root->rchild);
printf(")");
}
int main()
{
Node *root = reBuild(0, 9, 0, 9);
traverse(root);
return 0;
}
分治-二叉樹重建
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.