Find the K-th Ancestor of a Chosen Node
Implement kthAncestor
You are given the root of a binary tree with distinct node values, a value target and an integer k. The 1st ancestor of a node is its parent, the 2nd ancestor is its parent's parent, and so on up towards the root. Return the value of the k-th ancestor of the node that holds target. If the target is not in the tree, or the node has fewer than k ancestors, return -1.
You can record the path from the root and count back from its end, or let the recursion count the steps upward as it returns from the target.
Example 1:
Input: root = [15,8,22,4,11,19,30,2,6,9,13], target = 13, k = 2
Output: 8
Example 2:
Input: root = [15,8,22,4,11,19,30,2,6,9,13], target = 6, k = 3
Output: 15
Example 3:
Input: root = [15,8,22,4,11,19,30,2,6,9,13], target = 22, k = 2
Output: -1
+ 13 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ number of nodes ≤ 100, and every node value is distinct, 1 ≤ node.val ≤ 1000 - ●
target is a value between 1 and 1000 that may or may not be in the tree; 1 ≤ k ≤ 100 - ●
The tree is given as its root node; each node has a val, a left child and a right child - ●
The 1st ancestor of a node is its parent, the 2nd is the parent of its parent, and so on. Return the value of the k-th ancestor of the node holding target, or -1 if the target is not in the tree or the node has fewer than k ancestors
root =
target =
k =