zoukankan      html  css  js  c++  java
  • Lintcode---线段树构造||

    线段树是一棵二叉树,他的每个节点包含了两个额外的属性startend用于表示该节点所代表的区间。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] (max = 3)     [2, 3]  (max = 4)
            /                       /             
    [0, 0](max = 3)  [1, 1](max = 2)[2, 2](max = 1) [3, 3] (max = 4)


    思路:构造线段树,线段树中包含区间的开始,结束下标,以及区间内的最大值;
     
    构造方法与基本线段树构造方法相同,只是加了最大值的属性;


    /**
     * 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* buildTree(int start, int end, vector<int>& A) {
            if (start > end)
                return NULL;
    
            if (start == end) {
                return new SegmentTreeNode(start, end, A[start]);
            }
    
            SegmentTreeNode* root = new SegmentTreeNode(start, end, A[start]);
            int mid = (start + end) / 2;
            root->left = buildTree(start, mid, A);
            root->right = buildTree(mid + 1, end, A);
            root->max=max(root->left->max,root->right->max);
    
            return root;
        }
        SegmentTreeNode * build(vector<int>& A) {
            // write your code here
            if(A.empty())  
                return NULL;  
            return buildTree(0, A.size() - 1, A);
        }
    };
    
  • 相关阅读:
    压缩脚本文件
    通用的访问非公有字段(Field)和属性组件
    调用加了SSL签名的WebService
    [译作]Class in Jscript Part I
    在UpdatePanel中使用Menu出错的解决方案
    到处遍是ASP.NET AJAX Released
    也谈约定胜于配置
    如何使用Orcas的CSS功能
    Ext js 2.0 Overview(3) 组件生命周期
    一些非常有用的备忘录文档
  • 原文地址:https://www.cnblogs.com/Allen-rg/p/7115565.html
Copyright © 2011-2022 走看看