439.Segment Tree Build II-线段树的构造 II(中等题)

线段树的构造 II

  1. 题目

    线段树是一棵二叉树,他的每个节点包含了两个额外的属性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方法,构造出线段树

  2. 说明

    wiki:
    Segment Tree
    Interval Tree

  3. 样例

    给出[3,2,1,4],线段树将被这样构造
    这里写图片描述

  4. 题解

    递归构造线段树,max值得获取参看202.Segment Tree Query-线段树的查询(中等题)

/**
 * Definition of SegmentTreeNode:
 * public class SegmentTreeNode {
 *     public int start, end, max;
 *     public SegmentTreeNode left, right;
 *     public SegmentTreeNode(int start, int end, int max) {
 *         this.start = start;
 *         this.end = end;
 *         this.max = max
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     *@param A: a list of integer
     *@return: The root of Segment Tree
     */
    public SegmentTreeNode build(int[] A) {
        if (A.length == 0)
        {
            return null;
        }
        SegmentTreeNode root = new SegmentTreeNode(0,A.length-1,0);
        create(A,root);
        return root;
    }

    private int create(int[] A, SegmentTreeNode root)
    {
        if (root.start == root.end)
        {
            root.max = A[root.start];
            return root.max;
        }
        root.left = new SegmentTreeNode(root.start,(root.start+root.end)/2,0);
        root.right = new SegmentTreeNode((root.start+root.end)/2+1,root.end,0);
        root.max = Math.max(create(A,root.left),create(A,root.right));
        return root.max;
    }
}

Last Update 2016.11.18

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值