Is it possible to build a Fenwick tree in O(n)?

前端 未结 2 789
北海茫月
北海茫月 2020-12-23 18:45

Fenwick tree is a data structure which allows two kind of operations (you can augment it with more operations):

  • point update update(index, value)<
2条回答
  •  悲&欢浪女
    2020-12-23 19:01

    Here's the Java implementation:

    public BIT(long[] nums) {
            bit = new long[nums.length + 1]; //one-indexed
            for (int i = 1; i <= nums.length; i++) {
                bit[i] += nums[i - 1]; //update node
                if (i + (i & -i) <= nums.length) {
                    bit[i + (i & -i)] += bit[i]; //update parent
                }
            }
        }
    

    Same general idea as j_random_hacker's post: we update the current node and the next higher parent node, using the property that all children nodes will always be visited before their respective parent nodes

提交回复
热议问题