How to represent a non binary tree and how to do LCA on that tree?

偶尔善良 提交于 2019-12-03 13:46:06

Adjacency matrix sounds like a bad idea, it will be very sparse (most cells will be empty). Usually for n-ary trees (yes that's how they are called) you just follow the same strategy as with the binary tree, the difference is that a binary tree would have 2 fields representing the left and right children:

class Node<T> {
   T value;
   Node<T> left;
   Node<T> right;
}

Here you change those fields into a data structure like an array (static or dynamic):

class Node<T> {
   T value;
   List<Node<T>> children;
}

As for the LCA, are you planning on storing the parent pointer in the nodes? Are the values supposed to be a tree with unique values? Will the values be ordered in any way?

If no, but you can assume that the nodes are in the tree (although handling the other case is not that hard) then the LCA is very similar to what you've shown above. You just need to change the part where you get the Node left and Node right so that it traverses all 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 storing the dept in each node we can do better but at a storage cost.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!