In the last blog segment tree problem, using an array to represent the line segment tree, the successful AC, this article uses the binary tree to represent the line segment tree, review the binary tree, but the following paragraph with the binary tree code of the segment tree is not AC, because this code space complexity is much higher than the previous one with a structure array representation of the space complexity.
#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::D estory (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;
}
This article is from the "Snow Night Star" blog, please make sure to keep this source http://592669550.blog.51cto.com/5487419/1700529
Tree--building segment tree with binary tree