Skip to content

Commit 21aba1e

Browse files
authored
Update kth-ancestor-of-a-tree-node.cpp
1 parent 5228d59 commit 21aba1e

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

C++/kth-ancestor-of-a-tree-node.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ class TreeAncestor {
77
public:
88
TreeAncestor(int n, vector<int>& parent) {
99
for (const auto& p : parent) {
10-
parent_.emplace_back(vector<int>(1, p));
10+
parent_.emplace_back(vector<int>(p != -1, p));
1111
}
1212
for (int i = 0, max_depth = 1; i < max_depth; ++i) {
1313
for (auto& p : parent_) {
14-
if (!(i < p.size() && p[i] != -1)) {
14+
if (!(i < p.size() && i < parent_[p[i]].size())) {
1515
continue;
1616
}
17-
p.emplace_back((i < parent_[p[i]].size()) ? parent_[p[i]][i] : -1);
17+
p.emplace_back(parent_[p[i]][i]);
1818
if (p.size() > max_depth) {
1919
max_depth = p.size();
2020
}
@@ -25,7 +25,7 @@ class TreeAncestor {
2525
int getKthAncestor(int node, int k) {
2626
for (; k; k -= k & ~(k - 1)) {
2727
int i = __builtin_ctz(k & ~(k - 1));
28-
if (!(i < parent_[node].size() && parent_[node][i] != -1)) {
28+
if (!(i < parent_[node].size())) {
2929
return -1;
3030
}
3131
node = parent_[node][i];

0 commit comments

Comments
 (0)