algorithm - Calculate the number of nodes on either side of an edge in a tree -


a tree here means acyclic undirected graph n nodes , n-1 edges. each edge in tree, calculate number of nodes on either side of it. if on removing edge, 2 trees having a , b number of nodes, want find values a , b edges in tree (ideally in o(n) time).

intuitively feel multisource bfs starting "leaf" nodes yield answer, i'm not able translate code.

for credit, provide algorithm works in general graph.

run depth-first search (or breadth-first search if more) node. node called root node, , edges traversed in direction root node.

for each node, calculate number of nodes in rooted subtree. when node visited first time, set number 1. when subtree of child visited, add size of subtree parent.

after this, know number of nodes on 1 side of each edge. number on other side total minus number found.

(the credit version of question involves finding bridges in graph on top of non-trivial part, , deserves asked separate question if interested.)


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -