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

前端 未结 3 441
小蘑菇
小蘑菇 2021-01-14 10:13

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, wi

3条回答
  •  心在旅途
    2021-01-14 10:45

    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.

提交回复
热议问题