The displacement matrix sounds like a bad idea, it will be very scarce (most cells will be empty). Usually for n-ary trees (yes, as they are called) you just follow the same strategy as for a binary tree, the difference is that the binary tree will have 2 fields representing the left and right children:
class Node<T> { T value; Node<T> left; Node<T> right; }
Here you change these fields into a data structure such as an array (static or dynamic):
class Node<T> { T value; List<Node<T>> children; }
As for LCA , do you plan on storing the parent pointer in nodes? Do values ββmean like a tree with unique values? Will the values ββbe ordered in any way?
If not, but you can assume that the nodes are in the tree (although handling the other case is not so difficult), the LCA is very similar to what you showed above. You just need to change the part where you get Node left and Node right so that it goes through all the children:
int count = 0; Node<T> temp = null; for(Node<T> child : root.children) { Node<T> result = lca(child, v1, v2); if(result != null) { count++; temp = result; } } if(count == 2) { return root; } return temp;
With parent pointers and / or department storage in each node, we can do better, but at the cost of storage.
source share