Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the nth ancestor of a node in a binary search tree?

I got asked this at a job interview. Here's my O(log n) solution.

Find the depth of the node. Repeat the search, but stop at depth - n.

Is there a way to do this without the second pass?

like image 707
sigjuice Avatar asked Nov 14 '09 23:11

sigjuice


People also ask

How do you find the ancestors of a node in a binary tree?

Input the binary tree and the key_node whose ancestors are to be printed. Traverse all the nodes of the tree and perform recursive post order traversal. Until the key_node is found, traverse the left and right sub trees recursively. Once the key_node is reached, return the data of the nodes in the path.

How many ancestors does a node have in the nth level of a tree?

3. How many ancestors does a node at level n in a binary tree have? Answer: 2^(h+1)-1-2^i . h=height of the tree.

What is ancestor of a node?

A node that is connected to all lower-level nodes is called an "ancestor". The connected lower-level nodes are "descendants" of the ancestor node.


2 Answers

In your search for the node you can keep track of all nodes in the path from the current node to the root. This is a simple list with a length not greater than the depth of the tree. Once the node has been found, its nth ancestor is at position length - n in the list.

like image 190
Stephan202 Avatar answered Sep 19 '22 23:09

Stephan202


Your question is a bit wrong, I guess. You miss one important matter. Of course you can do it without second pass. Just maintain a queue of last n nodes in your search.

What you miss is that such algorithm needs O(log n) memory. While your solution trades off time consumption for memory usage, and uses O(1) (constant amount) of additional memory)

So your solution is not "wrong" or "too slow". It just has its own pros and cons.

like image 43
P Shved Avatar answered Sep 17 '22 23:09

P Shved