Kth Ancestor of node in a Binary tree

Pattern: Lowest common ancestor

medium

Record the path from the root down to the node. Its kth ancestor is k places before the node on that path, or -1 if the path is too short.

The problem

Return the value of the kth ancestor of the node with value node (the parent is the 1st), or -1 if it does not exist. Values are different. [1, 2, 3, 4, 5], k = 2, node = 4 gives 1. The function takes (root, k, node). Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What is the 1st ancestor?
  • Which list holds all ancestors in order?
  • When is there no answer?

Hints

    Brute force, and why it fails

    Build a parent map and step up k times: also O(n).

    The key insight

    The root-to-node path lists all ancestors in order, so the kth is a single index.

    Dry run

    path1 2 4

    Tree [1, 2, 3, 4, 5], node 4, k = 2. The path from the root is 1, 2, 4.

    Step 1 of 2

    The plan

    pathTo(n): add n; if n is the node or pathTo(left) or pathTo(right): return true; remove n; return false
    i = len(path) - 1 - k
    return path[i] if i >= 0 else -1
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    One search for the node.

    Edge cases

    • k larger than the depth: -1.
    • The node is the root: -1 for k ≥ 1.
    • k = 1: the parent.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int kthAncestor(TreeNode root, int k, int node) {
            List<Integer> path = new ArrayList<>();   // the values from the root down to node
            if (!pathTo(root, node, path)) return -1;
            int i = path.size() - 1 - k;
            return i >= 0 ? path.get(i) : -1;
        }
    
        private boolean pathTo(TreeNode n, int node, List<Integer> path) {
            if (n == null) return false;
            path.add(n.val);
            if (n.val == node || pathTo(n.left, node, path) || pathTo(n.right, node, path)) return true;
            path.remove(path.size() - 1);           // not on this side
            return false;
        }
    }

    C++

    class Solution {
    public:
        int kthAncestor(TreeNode* root, int k, int node) {
            vector<int> path;                       // the values from the root down to node
            if (!pathTo(root, node, path)) return -1;
            int i = static_cast<int>(path.size()) - 1 - k;
            return i >= 0 ? path[i] : -1;
        }
    
        bool pathTo(TreeNode* n, int node, vector<int>& path) {
            if (n == NULL) return false;
            path.push_back(n->val);
            if (n->val == node || pathTo(n->left, node, path) || pathTo(n->right, node, path)) return true;
            path.pop_back();                        // not on this side
            return false;
        }
    };

    Python

    class Solution:
        def kthAncestor(self, root, k: int, node: int) -> int:
            path = []                               # the values from the root down to node
    
            def path_to(n) -> bool:
                if n is None:
                    return False
                path.append(n.val)
                if n.val == node or path_to(n.left) or path_to(n.right):
                    return True
                path.pop()                          # not on this side
                return False
    
            if not path_to(root):
                return -1
            i = len(path) - 1 - k
            return path[i] if i >= 0 else -1

    Common mistakes

    • Counting the node itself as its 1st ancestor.
    • Indexing past the start of the path.

    Similar problems