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;
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7395485.html