线段树的构造 II-LintCode

来源:互联网 发布:python查找txt内容 编辑:程序博客网 时间:2024/06/08 07:33

线段树是一棵二叉树,他的每个节点包含了两个额外的属性start和end用于表示该节点所代表的区间。start和end都是整数,并按照如下的方式赋值:

  1. 根节点的 start 和 end 由 build 方法所给出。
  2. 对于节点 A 的左儿子,有 start=A.left, end=(A.left + A.right) / 2。
  3. 对于节点 A 的右儿子,有 start=(A.left + A.right) / 2 + 1, end=A.right。
  4. 如果 start 等于 end, 那么该节点是叶子节点,不再有左右儿子。

对于给定数组设计一个build方法,构造出线段树

样例:
给出[3,2,1,4],线段树将被这样构造

                  [0,  3] (max = 4)                  /            \           [0,  1] (max = 3)     [2, 3]  (max = 4)           /        \               /             \[0, 0](max = 3)  [1, 1](max = 2)[2, 2](max = 1) [3, 3] (max = 4)
#ifndef C439_H#define C439_H#include<iostream>#include<vector>using namespace std;class SegmentTreeNode{public:    int start, end, max;    SegmentTreeNode *left, *right;    SegmentTreeNode(int start, int end, int max)    {        this->start = start;        this->end = end;        this->max = max;        this->left = this->right = NULL;    }};class Solution {public:    /*    * @param A: a list of integer    * @return: The root of Segment Tree    */    SegmentTreeNode * build(vector<int> &A) {        // write your code here        int len = A.size();        SegmentTreeNode *root = buildRecur(A, 0, len - 1);        return root;    }    SegmentTreeNode* buildRecur(vector<int> &A, int i, int j)    {        if (i > j)            return NULL;        else if (i == j)        {            SegmentTreeNode *node = new SegmentTreeNode(i, i, A[i]);            return node;        }        else        {            SegmentTreeNode *node = new SegmentTreeNode(i, j, 0);            node->left = buildRecur(A, node->start, (node->start + node->end) / 2);            node->right = buildRecur(A, (node->start + node->end) / 2 + 1, node->end);            node->max = maxVal(node->left->max, node->right->max);            return node;        }    }    int maxVal(int a, int b)    {        return a > b ? a : b;    }};#endif
原创粉丝点击