• lintcode-439-线段树的构造 II


    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方法,构造出线段树

    说明

    wiki:
    Segment Tree
    Interval Tree

    样例

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

    标签

    线段树

    思路

    自底向上构造线段树

    code

    /**
     * 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 nullptr;
            }
            return build(0, A.size() - 1, A);
        }
        
        SegmentTreeNode * build(int start, int end, vector<int> &nums) {
            // write your code here
            if (start > end) {
                return nullptr;
            }
            SegmentTreeNode *root = new SegmentTreeNode(start, end, 0);
            if (start != end) {
                root->left = build(start, (start + end) / 2, nums);
                root->right = build((start + end) / 2 + 1, end, nums);
                root->max = max(root->left->max, root->right->max);
            }
            else {
                root->max = nums[start];
            }
            return root;
        }
    };
    
  • 相关阅读:
    LeetCode 重排链表算法题解 All In One
    上海图书馆 & 上海图书馆东馆 All In One
    北美 CS 专业 New Grad 工资组成部分 All In One
    Go Gin errors All In One
    人邮学院 All In One
    Leetcode 1512. 好数对的数目
    VS中创建和使用c++的dll动态库(转)
    通过HWND获得CWnd指针/通过CWnd获取HWND
    读文件使用QProgressBar显示进度
    R语言中apply函数的用法
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7395485.html
Copyright © 2020-2023  润新知