您的位置:首页 > 其它

ural 1136. Parliament 中后序建树

2015-08-20 13:56 316 查看
题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1136

题目描述:应用环境就不看了,摘要出来就是,给定后序序列,中序就是递增序,建树后按照它的遍历规则求新序列(先右后左再中间);

思路感觉还是蛮清晰的,后序序列从后往前插入二叉树,就可以还原了,受到启发其它的中序只要能够定义偏序比较就可以用类似的方法轻松建树!

上AC代码:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <map>
using namespace std;

struct Node{
Node *left, *right;
int id;
Node(int num) :id(num), left(nullptr), right(nullptr){}

void uniqTraversal(){
if (this->right != nullptr)
this->right->uniqTraversal();
if (this->left != nullptr)
this->left->uniqTraversal();
cout << this->id << endl;
}

};

void insertTree(Node* &ptr, int num){
if (ptr == nullptr)
ptr = new Node(num);
else if (num < ptr->id)
insertTree(ptr->left, num);
else
insertTree(ptr->right, num);
}

void func(){
int n, num, i;
Node* head = nullptr;
cin >> n;
vector<int>v;
for (i = 0; i < n; i++){
cin >> num;
v.push_back(num);
}
for (i = v.size() - 1; i >= 0; i--)
insertTree(head, v[i]);

head->uniqTraversal();
}

int main(){

freopen("out.txt", "w", stdout);
freopen("in.txt", "r", stdin);

func();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: