0%

[題解]NEOJ 48 二元搜尋樹

二元搜尋樹

題目連結
很特別的一題,原來BST 用中序遍歷就是排序好的數列!
有了前序跟中序之後,就可以透過遞迴來還原整棵二元樹了!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <bits/stdc++.h>
using namespace std;
int n;

struct Node{
Node *left;
Node *right;
int val;
};

Node* BinaryTree(int* preorder, int* inorder, int length){
if(length==0)return NULL;
Node *node = new Node;
node->val = *preorder;

int root_index = 0;
for(;root_index<length;root_index++){
if(inorder[root_index]==*preorder)break;
}
node->left = BinaryTree(preorder+1, inorder,root_index);
node->right = BinaryTree(preorder+root_index+1, inorder+root_index+1,length-root_index-1);
cout<<node->val<<endl;
return node;
}

signed main(){
int arr[2005],sorted[2005];
while(cin>>arr[n]){
sorted[n] = arr[n];
n++;
}
sort(sorted, sorted+n);
BinaryTree(arr, sorted, n);
}