又二叉树的特征,知道先序遍历的输出和中序遍历的输出,就可以还原一颗唯一的树。而在
二叉搜索树中,中序遍历恰恰是将先序遍历排序后的结果。所以给出先序遍历的输出结构,便可以
还原这棵二叉搜索树。
My Code
#include<iostream>
#include<stdio.h>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
const int maxn = 1009;
int pre[maxn]; //preorder
int mid[maxn]; //indorder
map<int,int> index; //index of value maxn in mid[]
//define the node of tree
struct Node{
int val;
Node *ls, *rs

根据二叉搜索树的特性,利用先序遍历的结果可以唯一地还原整棵树,因为先序遍历的顺序与中序遍历排序后的顺序一致。在实际编程中,这种方法可能会导致部分数据超时,具体原因待查。
最低0.47元/天 解锁文章
1605

被折叠的 条评论
为什么被折叠?



