Check if 2 nodes of the tree are connected (i.e. ancestor descendant)
- solve it O (1) times, with O (N) space (N = # nodes)
- pre-processing allowed.
What is it. I will move on to my decision below. Please stop if you want to think first.
For pre-processing, I decided to pre-order (recursively go through the root first, then the children) and give a label to each node.
Let me explain the shortcuts in detail. Each label will consist of comma separated natural numbers, such as "1,2,1,4,5" - the length of this sequence is (depth node + 1). For example. root label "1", root children will have labels "1,1", "1,2", "1,3", etc. The nodes of the next level will have labels like "1,1,1", "1,1,2", ..., "1,2,1", "1,2,2", ...
Suppose that the “order number” of a node is an “index based on 1 of this node” in its parent list.
General rule: the node label consists of its parent label, followed by a comma, and the "order number" of the node.
Thus, in order to answer if two nodes are connected in O (1) (i.e., the descendant ancestor), I will check whether the label of one of them is a “prefix” of the other label. Although I'm not sure that we can assume that such labels occupy O (N) space.
Any criticism is expected with corrections or an alternative approach.