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

前端 未结 4 1999
不思量自难忘°
不思量自难忘° 2021-02-14 08:49

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:49

    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).

提交回复
热议问题