Kth Ancestor of a Tree Node LeetCode solution in C++
1class TreeAncestor {2public:3// go up by only powers of two4vector<vector<int>> lift;5TreeAncestor(int n, vector<int> &parent) {6lift.resize(n, vector<int>(21, -1));7// every node's first ancestor is parent itself8for (int i = 0; i < n; ++i) lift[i][0] = parent[i];910for (int i = 0; i < n; ++i) {11for (int j = 1; j <= 20; ++j) {12if (lift[i][j - 1] == -1) continue;13lift[i][j] = lift[lift[i][j - 1]][j - 1];14}15}16}1718int getKthAncestor(int node, int k) {19for (int i = 0; i <= 20; ++i) {20if (k & (1 << i)) {21node = lift[node][i];22if (node == -1) break;23}24}25return node;26}27};