Algorithm- Sum of distances between every two nodes of a Binary Search Tree in O(n)?

前端 未结 4 1964
面向向阳花
面向向阳花 2021-02-14 09:05

The question is to find out sum of distances between every two nodes of BinarySearchTree given that every parent-child pair is separated by unit distance. It is to be calculated

4条回答
  •  深忆病人
    2021-02-14 09:27

    First, add four variables to every node. The four variables are sum of distance to the left offspring, sum of distance to the right offspring, number of node in left offspring and number of node in right offspring. Denote them as l, r, nl and nr.

    Second, add a total variable to root node to record the sum after each insertion.

    The idea is if you have total of current Tree, the new total after inserting a new node is (old total + sum of distance of new node to all other nodes). What you need to calculate in every insertion is sum of distance of new node to all other nodes.

    1- Insert the new node with four variable set to zero.
    2- Create two temp counter "node travel" and "subtotal" with value zero.
    3- Back trace the route from new node to root. 
       a- go up to parent node
       b- add one to node travel 
       c- add node travel to subtotal
       d- add (nr * node travel) + r to subtotal if the new node is on left offspring
       e- add node travel to l
       f- add one to nl
    4- Add subtotal to total
    

    1 - O(n)

    2 - O(1)

    3 - O(log n), a to f take O(1)

    4 - O(1)

提交回复
热议问题