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

前端 未结 4 1978
面向向阳花
面向向阳花 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:50

    If you mean O(n) per each insertion, then it can be done, assuming you do it after each and every insertion, starting with the root.

    0- Record the current sum of the distances. Call it s1: O(1).
    1- Insert the new node: O(n).
    2- Perform a BFS, starting at this new node.
       For each new node you discover, record its distance to the start (new) node, as BFS always does: O(n).
       This gives you an array of the distances from the start node to all other nodes.
    3- Sum these distances up. Call this s2: O(n).
    4- New_sum = s1 + s2: O(1).
    

    This algorithm is thus O(n).

提交回复
热议问题