lintcode 439. 线段树的构造 II

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

根节点的 start 和 end 由 build 方法所给出。
对于节点 A 的左儿子,有 start=A.left, end=(A.left + A.right) / 2。
对于节点 A 的右儿子,有 start=(A.left + A.right) / 2 + 1, end=A.right。
如果 start 等于 end, 那么该节点是叶子节点,不再有左右儿子。
对于给定数组实现build方法, 线段树的每个节点储存区间最大值, 返回根节点.

样例
输入: [3,2,1,4]
解释: 
这颗线段树将会是
          [0,3](max=4)
          /          \
       [0,1]         [2,3]    
      (max=3)       (max=4)
      /   \          /    \    
   [0,0]  [1,1]    [2,2]  [3,3]
  (max=3)(max=2)  (max=1)(max=4)
说明
线段树(又称区间树)是一种高级数据结构, 支持一系列区间查询/修改操作.

维基百科: https://zh.wikipedia.org/zh-hans/線段樹
/**
 * Definition of SegmentTreeNode:
 * 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
        if(A.size()<=0) return NULL;
        return build(A,0,A.size()-1);
    }
    SegmentTreeNode*build(vector<int>&A,int start,int end)
    {
        SegmentTreeNode*node;
        if(start!=end)
            node=new SegmentTreeNode(start,end,0);
        else
            node=new SegmentTreeNode(start,end,A[start]);
        if(start==end) return node;
        node->left=build(A,start,(start+end)/2);
        node->right=build(A,(start+end)/2+1,end);
        node->max=max(node->left->max,node->right->max);
        return node;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值