For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc. Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. These information allow us to jump from a
(tree *Tree)
| 111 | // Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. |
| 112 | // These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time. |
| 113 | func LowestCommonAncestor(tree *Tree) { |
| 114 | // call dfs to compute depth from the root to each node and the parent of each node. |
| 115 | tree.dfs(tree.root, tree.root) |
| 116 | |
| 117 | // compute jump[j][u] |
| 118 | for j := 1; j < tree.MAXLOG; j++ { |
| 119 | for u := 0; u < tree.numbersVertex; u++ { |
| 120 | tree.jump[j][u] = tree.jump[j-1][tree.jump[j-1][u]] |
| 121 | } |
| 122 | } |
| 123 | } |