cartesianTree 发表于 2020-03-16 分类于 数据结构 阅读次数: 本文字数: 2.1k 阅读时长 ≈ 2 分钟 nexthexonextbutterflyvolantisyearnyiliashokaindigoapollolandscapecactusmateryicarusfluidmaterial cartesian tree 笛卡尔树是一颗二叉树,他满足中序遍历为维护的序列,且满足堆的性质 build 我们使用单调栈来维护树根到叶子的链,在单调栈的构建中完成树的构建 ct代码 treeview raw123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596/*#pragma once#include <iostream>#include <sstream>#include <stack>#include <string>#include <vector>#include "../memery_management/memery_pool.h"#include "tree.h"template <class T>class CT { struct node { node *ls, *rs; T key; }; memery_pool<node> pool; node* root = nullptr; node* newnode(const T& w) { node* res = pool.get(); res->ls = res->rs = nullptr; res->key = w; return res; } void preorder(node*& rt, void (*f)(const T&)) { if (rt == nullptr) return; f(rt->key); preorder(rt->ls, f); preorder(rt->rs, f); } void midorder(node*& rt, void (*f)(const T&)) { if (rt == nullptr) return; midorder(rt->ls, f); f(rt->key); midorder(rt->rs, f); } void erase(node*& rt) { if (rt == nullptr) return; erase(rt->ls); erase(rt->rs); pool.erase(rt); } public: CT() { root = nullptr; } void preorder(void (*f)(const T&)) { preorder(root, f); } void midorder(void (*f)(const T&)) { midorder(root, f); } void build(T* a, int n) { std::stack<node*> s; // 栈中维护从根到叶子的链 std::vector<node*> v; for (int i = 0; i < n; i++) { while (!s.empty() && a[i] > s.top()->key) { v.push_back(s.top()); s.pop(); } for (unsigned int i = 1; i < v.size(); i++) { v[i]->rs = v[i - 1]; } s.push(newnode(a[i])); if (!v.empty()) { s.top()->ls = v.back(); v.clear(); } } while (!s.empty()) { v.push_back(s.top()); root = s.top(); s.pop(); } for (unsigned int i = 1; i < v.size(); i++) { v[i]->rs = v[i - 1]; } v.clear(); } void clear() { erase(root); }};void test() { using namespace std; CT<int> tree; while (true) { string input; getline(cin, input); stringstream line(input); vector<int> v; int x; while (line >> x) v.push_back(x); CT<int> ct; ct.build(v.data(), v.size()); ct.preorder([](const int& w) { cout << w; }); cout << endl; ct.midorder([](const int& w) { cout << w; }); cout << endl; }}*/