Java Algorithm for finding the largest set of independent nodes in a binary tree

岁酱吖の 提交于 2019-12-01 07:55:17

问题


By independent nodes, I mean that the returned set can not contain nodes that are in immediate relations, parent and child cannot both be included. I tried to use Google, with no success. I don't think I have the right search words.

A link, any help would be very much appreciated. Just started on this now.

I need to return the actual set of independent nodes, not just the amount.


回答1:


You can compute this recursive function with dynamic programming (memoization):

MaxSet(node) = 1 if "node" is a leaf
MaxSet(node) = Max(1 + Sum{ i=0..3: MaxSet(node.Grandchildren[i]) },  
                       Sum{ i=0..1: MaxSet(node.Children[i])      })

The idea is, you can pick a node or choose not to pick it. If you pick it, you can't pick its direct children but you can pick the maximum set from its grandchildren. If you don't pick it, you can pick maximum set from the direct children.

If you need the set itself, you just have to store how you selected "Max" for each node. It's similar to the LCS algorithm.

This algorithm is O(n). It works on trees in general, not just binary trees.




回答2:


I would take-and-remove all leaves first while marking their parents as not-to-take, then remove all leaves that are marked until no such leaves are left, then recurse until the tree is empty. I don't have a proof that this always produces the largest possible set, but I believe it should.




回答3:


I've provided an answer to a question for the same problem, although the solution is in python, the explanation, algorithm, and test cases could be applicable.



来源:https://stackoverflow.com/questions/1567532/java-algorithm-for-finding-the-largest-set-of-independent-nodes-in-a-binary-tree

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