解題報告:線段樹的修改

http://www.lintcode.com/zh-cn/problem/segment-tree-modify/

/**
 * 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->end == root->start){ 
			root->max = value; return;
		}
		int mid = root->start + (root->end - root->start) / 2;
		if (mid < index){
			modify(root->right, index, value); 
		}
		else{
			modify(root->left, index, value);
		}
		root->max = max(root->right->max, root->left->max);
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章