← Home

1483. Kth Ancestor of a Tree Node

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
148

This is one of those problems where the clean idea matters more than the amount of code. For 1483. Kth Ancestor of a Tree Node, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, bit manipulation.

The notes already sitting in the source point us in the right direction:

  • TLE
  • 9 / 10 test cases passed.
  • class Node{
  • public:

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are getKthAncestor.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//9 / 10 test cases passed.
03// class Node{
04// public:
05//     Node* parent;
06//     vector<Node*> children;
07//     int val;
08    
09//     Node(int v){
10//         val = v;
11//     }
12// };
13
14class TreeAncestor {
15public:
16    // vector<vector<int>> paths;
17    // Node* root;
18    // vector<Node*> nodes;
19    vector<int> parent;
20    
21    TreeAncestor(int n, vector<int>& parent) {
22        this->parent = parent;
23//         for(int i = 0; i < parent.size(); i++){
24//             nodes.push_back(new Node(i));
25//         }
26        
27//         for(int i = 0; i < parent.size(); i++){
28//             if(parent[i] == -1){
29//                 root = nodes[i];
30//             }else{
31//                 Node* pnode = nodes[parent[i]];
32//                 pnode->children.push_back(nodes[i]);
33//             }
34//         }
35    }
36    
37    int getKthAncestor(int node, int k) {
38        while(k-- >0 && node != -1){
39            node = parent[node];
40        }
41        
42        return node;
43    }
44};
45
46/**
47 * Your TreeAncestor object will be instantiated and called as such:
48 * TreeAncestor* obj = new TreeAncestor(n, parent);
49 * int param_1 = obj->getKthAncestor(node,k);
50 */
51
52//dp
53//binary lifting
54//https://leetcode.com/problems/kth-ancestor-of-a-tree-node/discuss/686362/JavaC%2B%2BPython-Binary-Lifting
55//Runtime: 844 ms, faster than 71.18% of C++ online submissions for Kth Ancestor of a Tree Node.
56//Memory Usage: 107.3 MB, less than 100.00% of C++ online submissions for Kth Ancestor of a Tree Node.
57//class TreeAncestor {
58public:
59    int maxJump;
60    vector<vector<int>> jump;
61    
62    TreeAncestor(int n, vector<int>& parent) {
63        /*
64        for a tree of n nodes,
65        we can jump at most "maxJump" times
66        */
67        maxJump = ceil(log(n));
68        //from 0 to maxJump
69        jump = vector<vector<int>>(maxJump+1, vector<int>(n));
70        
71        //jump 2^0 steps upward
72        jump[0] = parent;
73        
74        for(int j = 1; j <= maxJump; j++){
75            for(int node = 0; node < n; node++){
76                //from node, jump 2^(j-1) steps upward
77                int halfway = jump[j-1][node];
78                jump[j][node] = (halfway == -1) ? -1 : jump[j-1][halfway];
79            }
80        }
81    }
82    
83    int getKthAncestor(int node, int k) {
84        int j = maxJump;
85        while(node != -1 && k > 0){
86            if(k >= (1 << j)){
87                node = jump[j][node];
88                k -= (1 << j);
89            }else{
90                j--;
91            }
92        }
93        /*
94        jump out the loop when either node doesn't exist or 
95        we have jump all k steps upward
96        */
97        return node;
98    }
99};
100
101/**
102 * Your TreeAncestor object will be instantiated and called as such:
103 * TreeAncestor* obj = new TreeAncestor(n, parent);
104 * int param_1 = obj->getKthAncestor(node,k);
105 */
106
107//dp + bit manipulation
108//https://leetcode.com/problems/kth-ancestor-of-a-tree-node/discuss/686362/JavaC%2B%2BPython-Binary-Lifting
109//fails when set "maxJump = ceil(log(n));" (log is different from log2!!)
110//Runtime: 556 ms, faster than 90.22% of C++ online submissions for Kth Ancestor of a Tree Node.
111//Memory Usage: 110.3 MB, less than 100.00% of C++ online submissions for Kth Ancestor of a Tree Node.
112class TreeAncestor {
113public:
114    int maxJump;
115    vector<vector<int>> jump;
116    
117    TreeAncestor(int n, vector<int>& parent) {
118        /*
119        for a tree of n nodes,
120        we can jump at most "maxJump" times
121        */
122        //notice the difference between log(it's natural log!) and log2(2-based)!!!
123        maxJump = ceil(log2(n))+1;
124        // maxJump = 20;
125        //from 0 to maxJump
126        jump = vector<vector<int>>(maxJump+1, vector<int>(n));
127        
128        //jump 2^0 steps upward
129        jump[0] = parent;
130        
131        for(int j = 1; j <= maxJump; j++){
132            for(int node = 0; node < n; node++){
133                //from node, jump 2^(j-1) steps upward
134                int halfway = jump[j-1][node];
135                jump[j][node] = (halfway == -1) ? -1 : jump[j-1][halfway];
136            }
137        }
138    }
139    
140    int getKthAncestor(int node, int k) {
141        // cout << "k: " << k << ", j: ";
142        for(int j = 0; j <= maxJump; j++){
143            if(k & (1 << j)){
144                /*
145                view "k" as a bitset,
146                and we are decompose "k" into the powers of 2
147                when "k"'s "j"th bit is set,
148                that means one of the component of k is 2^j,
149                so we jump up 2^j steps upward
150                */
151                // cout << j << " ";
152                node = jump[j][node];
153                if(node == -1) break;
154            }
155        }
156        // cout << endl;
157        return node;
158    }
159};
160
161/**
162 * Your TreeAncestor object will be instantiated and called as such:
163 * TreeAncestor* obj = new TreeAncestor(n, parent);
164 * int param_1 = obj->getKthAncestor(node,k);
165 */

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.