2

In an algorithmic problem that I'm trying to solve - I'm in a situation where I'm given a tree and I need to select a node as a root for which the tree height would be minimum.

There are 200,000 nodes and 150,000 edges. Because of time constraint, I need a better algorithm than O(n^2).

What algorithm can I use?

Donotalo
  • 12,748
  • 25
  • 83
  • 121
  • 3
    So, what you are looking for is called the center of the tree, which has been discussed [here](http://stackoverflow.com/questions/4020122/finding-center-of-the-tree) – Pham Trung Dec 16 '15 at 07:09
  • @PhamTrung: Good. Thank you. I didn't know the term center of the tree. Why don't you post it as an answer so that I can choose it as best answer? – Donotalo Dec 16 '15 at 07:23

2 Answers2

2

I think the center of the tree should be the required node as root of the tree, because the maximum distance from root to any node is minimum if the root is center of the tree.

Daga
  • 334
  • 2
  • 14
1

Pick any node and assume it's the root. Run a DFS to find the distance to the furthest leaf. This will basically calculate the height of the tree if you pick the first node as root.

Next you find the proper root by finding the center of the tree. To do this you look at the children of the current root and pick the one with the largest height (largest distance to the furthest leaf). If you move the root to that child the new height will be min between the value you already have in that node and 1 + the next largest value from the other leafs of the current root. You apply this, moving the root until you can't decrease the height anymore. That is one center of the tree (could be more) and a solution that you are looking for.

The inital DFS is O(N). When optimizing the distance you can't visit a node twice and each step is O(1) amortized, so overall it's O(N). O(1) amortized because a node can have lots of children but you only consider them once (after you move you can't go back so you can't check them again) so even if you check the entire tree you'll check O(N) children in total.

Sorin
  • 11,863
  • 22
  • 26