Lintcode---线段树修改

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

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

 注意事项

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

样例

对于线段树:

                      [1, 4, max=3]
                    /                
        [1, 2, max=2]                [3, 4, max=3]
       /                           /             
[1, 1, max=2], [2, 2, max=1], [3, 3, max=0], [4, 4, max=3]

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

                      [1, 4, max=4]
                    /                
        [1, 2, max=4]                [3, 4, max=3]
       /                           /             
[1, 1, max=2], [2, 2, max=4], [3, 3, max=0], [4, 4, max=3]

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

                      [1, 4, max=2]
                    /                
        [1, 2, max=2]                [3, 4, max=0]
       /                           /             
[1, 1, max=2], [2, 2, max=1], [3, 3, max=0], [4, 4, max=0]



思路:首先清楚最大线段树的定义,然后,还是利用线段树的性质,分析清楚基准情形,利用递归来求解。
     使用递归,虽然速度慢了些,但对于复杂问题,理解起来更容易,思路更清晰。
         
     先找到index所在叶子节点,并修改该叶子节点的值,然后再从下往上依次更新其父节点的max值。

/**
 * 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
     */
    /*
    思路:首先清楚最大线段树的定义,然后,还是利用线段树的性质,分析清楚基准情形,
          利用递归来求解。
          使用递归,虽然速度慢了些,但对于复杂问题,理解起来更容易,思路更清晰。
          
          先找到index所在叶子节点,并修改该叶子节点的值,然后再从下往上依次更新其父节点的max。
    */
    void modify(SegmentTreeNode *root, int index, int value) {
        // write your code here
        
        if(root==NULL){
            return;
        }
        
        if(index>root->end||index<root->start){
            return;
        }
        
        if(index==root->start&&root->start==root->end){
            root->max=value;
            return;
        }

        
        modify(root->left,index,value);  
        modify(root->right,index,value);
        
        root->max=max(root->left->max,root->right->max);
    }
};
 
原文地址:https://www.cnblogs.com/Allen-rg/p/7087506.html