• lintcode-203-线段树的修改


    203-线段树的修改

    对于一棵 最大线段树, 每个节点包含一个额外的 max 属性,用于存储该节点所代表区间的最大值。
    设计一个 modify 的方法,接受三个参数 root、 index 和 value。该方法将 root 为跟的线段树中 [start, end] = [index, index] 的节点修改为了新的 value ,并确保在修改后,线段树的每个节点的 max 属性仍然具有正确的值。

    注意事项

    在做此题前,最好先完成线段树的构造和 线段树查询这两道题目。

    样例

    对于线段树:

    如果调用 modify(root, 2, 4), 返回:

    或 调用 modify(root, 4, 0), 返回:

    挑战

    时间复杂度 O(h) , h 是线段树的高度

    标签

    LintCode 版权所有 二叉树 线段树

    思路

    利用递归, 自底向上 修改线段树

    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 root, index, value: The root of segment tree and 
         *@ change the node's value with [index, index] to the new given value
         *@return: void
         */
        void modify(SegmentTreeNode *root, int index, int value) {
            // write your code here
            if (root == NULL) {
                return;
            }
            if (root->start == root->end) {
                if (root->start == index) {
                    root->max = value;
                }
                return;
            }
            modify(root->left, index, value);
            modify(root->right, index, value);
    
            root->max = max(root->left->max, root->right->max);
        }
    };
    
  • 相关阅读:
    第三章-列表简介
    第二章—变量和简单数据类型
    CSS3转换
    maven项目报:An error occurred while filtering resources
    CSS基本知识和选择器
    Html
    算法(第四版)学习笔记(三)——归并排序
    算法学习笔记(二)——初级排序算法
    算法学习(一)——二分查找递归方法
    1003. 我要通过!(20)
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7301378.html
Copyright © 2020-2023  润新知