上一博文线段树问题中,用数组表示线段树,成功AC了,本文用二叉树表示线段树,复习一下二叉树,不过下面这段用二叉树代码表示的线段树是无法AC的,因为这个代码的空间复杂度远高于上一个用结构体数组表示的空间复杂度。
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<list>
#include<iterator>
#include<string>
#include<stack>
using namespace std;
#define INF 0x3fffffff
struct NODE {
int left, right, value;
};
struct Tree {
NODE node;
Tree *left, *right;
};
class SegTree {
public:
SegTree() {
}
~SegTree() {
}
void Build(Tree *t,int n,int left,int right);
int Find(Tree *t, int n, int begin, int end);
void Update(Tree *t, int n, int ind, int val);
void Destory(Tree *t);
};
void SegTree::Build(Tree *t, int n, int left,int right){
t->node.left = left;
t->node.right = right;
if (left == right)
{
scanf("%d", &t->node.value);
return;
}
int mid = (left + right) >> 1;
t->left = new Tree();
Build(t->left,n << 1, left, mid);
t->right = new Tree();
Build(t->right,(n << 1) + 1, mid + 1, right);
t->node.value = min(t->left->node.value, t->right->node.value);
}
int SegTree::Find(Tree *t,int n, int begin, int end) {
int p1 = INF, p2 = INF;
if (t->node.left >= begin&&t->node.right <= end)
return t->node.value;
if (begin <= t->left->node.right)
p1 = Find(t->left,n << 1, begin, end);
if (end >= t->right->node.left)
p2 = Find(t->right,(n << 1) + 1, begin, end);
return min(p1, p2);
}
void SegTree::Update(Tree *t,int n, int ind, int val) {
if (t->node.left == t->node.right)
{
t->node.value = val;
}
else
{
if (ind <= t->left->node.right)
Update(t->left,n << 1, ind, val);
if (ind >= t->right->node.left)
Update(t->right,(n << 1) + 1, ind, val);
t->node.value = min(t->left->node.value, t->right->node.value);
}
}
void SegTree::Destory(Tree *t) {
Destory(t->left);
Destory(t->right);
delete t;
t = NULL;
}
int main()
{
int N;
int m;
int s, l, r;
SegTree st;
Tree *t = new Tree();
while (~scanf("%d", &N))
{
st.Build(t,1, 0, N - 1);
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
scanf("%d %d %d", &s, &l, &r);
if (s == 0)
printf("%d\n", st.Find(t,1, l - 1, r - 1));
if (s == 1)
st.Update(t,1, l - 1, r);
}
}
st.Destory(t);
return 0;
}