<LeetCode> 题203:线段树的修改

来源:互联网 发布:软件开发图标素材 编辑:程序博客网 时间:2024/06/10 04:26

题目描述:

对于一棵 最大线段树, 每个节点包含一个额外的 max 属性,用于存储该节点所代表区间的最大值。

设计一个 modify 的方法,接受三个参数 root、 index 和value。该方法将 root 为根的线段树中[start, end] = [index, index]的节点修改为了新的 value ,并确保在修改后,线段树的每个节点的 max 属性仍然具有正确的值。

例如:
对于线段树:
这里写图片描述
如果调用 modify(root, 2, 4), 返回:
这里写图片描述
或 调用 modify(root, 4, 0), 返回:
这里写图片描述

数据结构:

/** * 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:    void modify(SegmentTreeNode *root, int index, int value)    {        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);      }};
0 0
原创粉丝点击